Here's my 2 classes
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);
}
I want a grouped collection that looks something like this
sub1 -> item1, item2, item3
sub2 -> item1, item3 sub3 -> item2, item3How can I accomplish this?
Thanks much!
I'm assuming item1, item2, item3 are part of a new List<Item>
whose name is 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 };
Something like this i v4.0?
new[]{ item1, item2 ,item3 }
.SelectMany(i => i.Subs,(i,s)=>new { Sub=s,Item=i })
.ToLookup(l=>l.Sub,l=>l.Item)
I dont know if that'll work in 3.5 though
This is one way:
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()
};
精彩评论