LINQ将项目分组为匿名类型的列表,具有重复项

时间:2014-05-23 04:59:27

标签: c# linq

我有3个可以包含水果的盒子:

  

A - 苹果,橘子,梨

     

B - 苹果,香蕉

     

C - 梨子

我想创建一个LINQ查询语句,该语句生成一个新的匿名类型,按照它们包含的水果(不是实际代码)对方框进行分组:

fruitBoxes.apples = {A, B}
fruitBoxes.oranges = {A}
fruitBoxes.bananas = {B}
fruitBoxes.pears = {A, C}

2 个答案:

答案 0 :(得分:2)

所有匿名类型属性必须在编译时知道,因此除非您确切知道要处理的内容(不太可能),否则不能使用匿名类型。

您可以改为使用Dictionary<string, List<string>>

var result = boxes.SelectMany(b => b.Fruits.Select(f => new { Box = b, Fruit = f }))
                  .GroupBy(x => x.Fruit, x => x.Box.Name)
                  .ToDictionary(g => g.Key, g => g.ToList());

Box定义为:

class Box
{
    public string Name { get; set; }
    public List<string> Fruits { get; set; }
}

答案 1 :(得分:0)

你可以这样做:

var boxes = new []
{
    new { box = "A", fruit = new [] { "apples", "oranges", "pears", }, },
    new { box = "B", fruit = new [] { "apples", "bananas", }, },
    new { box = "C", fruit = new [] { "pears", }, },
};

var query =
    from b in boxes
    from f in b.fruit
    group b.box by f into bs
    select new
    {
        fruit = bs.Key,
        boxes = bs.ToArray(),
    };

结果我明白了:

result