LINQ帮助,按对象中的一组项目分组

时间:2011-03-21 20:46:44

标签: c# linq .net-3.5 linq-to-objects

这是我的2个班级

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 - &gt; item1,item2,item3

sub2 - &gt; item1,item3

sub3 - &gt;第2项,第3项

我该如何做到这一点?

非常感谢!

3 个答案:

答案 0 :(得分:3)

我假设item1,item2,item3是新List<Item>的一部分,其名称为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 };

答案 1 :(得分: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中使用

答案 2 :(得分:0)

这是一种方式:

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