让我们说我有以下课程:
public class ObjectA
{
public string PropertyA { get; set; }
public List<string> ListProperty { get; set; }
}
和这样的集合类:
public class CollectionB
{
public List<ObjectA> Collection { get; set; }
}
这样使用:
public void MethodC(CollectionB coll)
{
coll.Add(new ObjectA
{
PropertyA = "merry"
ListProperty = new List<string> { "foo", "bar" }
});
coll.Add(new ObjectA
{
PropertyA = "xmas"
ListProperty = new List<string> { "yee", "har", "foo" }
});
coll.Add(new ObjectA
{
PropertyA = "folks"
ListProperty = new List<string> { "bar", "bah", "humbug" }
});
}
如何使用ObjectA的IGrouping<string, ObjectA>
属性字符串作为键(PropertyList
,"foo"
等)从CollectionB创建"bar"
?
小组中的重复不要打扰我。
答案 0 :(得分:2)
list.SelectMany(t => t.ListProperty.Select(q => new { ObjectA = t, Prop = q })).GroupBy(t => t.Prop, w=>w.ObjectA)
答案 1 :(得分:1)
对于这些设置,我更喜欢查询语法:
from a in coll from p in a.ListProperty group a by p
附注:以上内容将创建IEnumerable<IGrouping<string, ObjectA>>
要获取列表,只需使用(from a in coll from p in a.ListProperty group a by p).ToList()