2011-03-21 42 views
1

這裏是我的2班LINQ的幫助下,通過一系列項目的組中的對象

public class Item 
{ 
    public string Path { get; set; } 
    public List<Sub> Subs { get; set; } 
} 

public class Sub 
{ 
    public string Name { get; set; } 
} 

private void Test() 
{ 
    Sub sub1 = new Sub() { Name = "SUB1" }; 
    Sub sub2 = new Sub() { Name = "SUB2" }; 
    Sub sub3 = new Sub() { Name = "SUB3" }; 

    Item item1 = new Item() { Path = "/Path1" }; 
    Item item2 = new Item() { Path = "/Path2" }; 
    Item item3 = new Item() { Path = "/Path3" }; 

    item1.Subs.Add(sub1); 
    item1.Subs.Add(sub2); 

    item2.Subs.Add(sub1); 
    item2.Subs.Add(sub3); 

    item3.Subs.Add(sub1); 
    item3.Subs.Add(sub2); 
    item3.Subs.Add(sub3); 

    List<Item> items = new List<Item>(); 
    items.Add(item1); 
    items.Add(item2); 
    items.Add(item3); 
} 

我想要一個分組集合,看起來像這樣

SUB1 - >項目1,項目2,項目3

SUB2 - >項目1,項目3

SUB3 - >項目2,項目3

我怎樣才能做到這一點?

非常感謝!

回答

3

我假設物品1的工作,項目2,項目3是他的名字是items

//List<Item> items = new List<Item>(); 
//items.Add(item1); 
//items.Add(item2); 
//items.Add(item3); 

var groupedBySub = from item in items 
        from s in item.Subs 
        group item by s into g 
        select new{ Sug = g.Key, Items = g }; 
+0

非常感謝!!!! – Tom 2011-03-21 21:13:39

+1

哇,你的解決方案很乾淨簡單,謝謝! – Ateik 2012-09-19 05:48:01

0

像這樣的東西我v4.0?

new[]{ item1, item2 ,item3 } 
    .SelectMany(i => i.Subs,(i,s)=>new { Sub=s,Item=i }) 
    .ToLookup(l=>l.Sub,l=>l.Item) 

我不知道這是否會在3.5,雖然

0

這是一個新的List<Item>部分單程:

var items = new[] {item1, item2, item3}; 

     var result = from s in items.SelectMany((i, index) => i.Subs) 
        group s by s.Name 
        into g 
        select new { 
         Sub = g.Key, 
         Items = items 
          .Where(i => i.Subs.Any(s => s.Name == g.Key)) 
          .Select(i => i) 
          .ToList() 
        };