如果没有输入和输出,很难解释这一点。我制作了一个简单的汽车示例,以避免我的项目出现不必要的细节。
我有这个列表:
List<car> cars = new List<car>()
{
new car() { carname = "bmw", carwheels = new List<int>() { 1, 2, 3, 4 } },
new car() { carname = "cadillac", carwheels = new List<int>() { 1, 2, 3, 4 } },
new car() { carname = "mustang", carwheels = new List<int>() { 1, 2, 3, 4 } }
};
我想用扩展类输出这个:
{
{ carname = "bmw", carwheel = 1 },
{ carname = "bmw", carwheel = 2 },
{ carname = "bmw", carwheel = 3 },
{ carname = "bmw", carwheel = 4 },
{ carname = "cadillac", carwheel = 1 },
{ carname = "cadillac", carwheel = 2 },
{ carname = "cadillac", carwheel = 3 },
{ carname = "cadillac", carwheel = 4 },
{ carname = "mustang", carwheel = 1 },
{ carname = "mustang", carwheel = 2 },
{ carname = "mustang", carwheel = 3 },
{ carname = "mustang", carwheel = 4 }
}
有没有办法通过 IEnumerable 扩展方法进行投影?与 SelectMany() 相反的东西。
它不是 SelectMany()
的相反,而是 SelectMany()
的用途。你可以这样实现:
var result = cars.SelectMany(c =>
c.carwheels.Select(w => new
{
carname = c.carname,
carwheel = w
})).ToList();
内部 Select
将每辆汽车的车轮转换到一个新对象(在我的代码中是具有您指定属性的匿名类型)。外层的 SelectMany()
将这些序列扁平化为一个列表。
我是一名优秀的程序员,十分优秀!