没有输入和输出,很难解释这一点。我制作了一个简单的Car示例,以避免不必要的项目细节。

我有这个清单:

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()将这些序列拼合为一个列表。

10-02 01:58