2
public class Vehicle {
    public string Type
    public List<Color> Colors;
}

public class Result {
    public string Type
    public string Color;
}

Result从如下所示的查询中得到一个 's 列表:

Car   ->  Red
Car   ->  Blue
Boat  ->  Brown
Boat  ->  Yellow
Boat  ->  Green
Plane ->  White

我想List<Vehicle>用 LINQ 选择这个列表。我试过了,但没有用:

var List<Vehicle> = results.Select(v => new Vehicle
    {
    Type = v.Type;
    Colors = new List<Color> { new Color = v.Color }
    }

我确定我需要在这里使用某种组,但我不确定如何。

4

2 回答 2

3

听起来应该通过GroupBy电话进行:

var query = input.GroupBy(x => x.Type, x => x.Color)
                 .Select(g => new Vehicle { Type = g.Key, Colors = g.ToList() })
                 .ToList();

请注意,还有另一个重载GroupBy允许您跳过Select调用,但我认为这样做更简单。让我知道您是否需要其他形式。

请注意,如果您真的不需要在Vehicle对象中使用这些,您可以只使用Lookup

var lookup = input.ToLookup(x => x.Type, x => x.Color);

foreach (var color in lookup["Car"])
{
    // ...
}

That's handy if you only need the results within the specific method that you're querying it, but creating a List<Vehicle> would make more sense if you're propagating the data elsewhere.

于 2012-11-30T14:59:17.243 回答
0
results.GroupBy(r => r.Type)
       .Select(g => new Vehicle { 
                                   Type = g.Key, 
                                   Colors = t.Select(p => p.Color).ToList()
                                })
       .ToList()
于 2012-11-30T14:57:59.770 回答