2014-05-23 48 views
0

我有3个盒可以含有水果:LINQ组项目到匿名类型列表,其中重复

A - 苹果,桔子,梨

乙 - 苹果,香蕉

Ç - 梨

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

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

回答

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; } 
} 
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