我的课程Parent
包含Child
个对象的集合,其中Child
有两个属性:Key
和Value
:
class Parent
{
public IEnumerable<Child> Children { get; set; }
}
class Child
{
public String Key { get; set; }
public String Value { get; set; }
}
我需要将List<Parent>
分组为Child.Value
。
示例:
IEnumerable<Parent> parents = new List<Parent>()
{
new Parent()
{
Children = new List<Child>()
{
new Child() { Key = "key1", Value = "v1" },
new Child() { Key = "key1", Value = "v2" }
}
},
new Parent()
{
Children = new List<Child>()
{
new Child() { Key = "key1", Value = "v2" },
new Child() { Key = "key1", Value = "v3" }
}
}
};
任何方法?
答案 0 :(得分:3)
这对你有用吗?
var query =
from p in parents
from c in p.Children
group p by c.Value;
这给出了:
您也可以使用:
var query =
parents
.SelectMany(p => p.Children, (p, c) => new { p, c })
.GroupBy(x => x.c.Value, x => x.p);
这是一个即使Children
为null
或空可枚举的查询:
var query =
parents
.SelectMany(p =>
(p.Children ?? new Child[] { })
.DefaultIfEmpty(new Child() { Value = null }),
(p, c) => new { p, c })
.GroupBy(x => x.c.Value, x => x.p);
答案 1 :(得分:2)
您可以使用链式Linq
的{{3}}和SelectMany
:
var result = parents
.SelectMany(parent => parent.Children,
(parent, child) => new { Key = child.Value, Parent = parent })
.GroupBy(x => x.Key,
x => x.Parent);
逻辑上做的是:
Child
(使用展平GroupBy
),选择Child
的{{1}}作为value
及其Key
Parent
- Key
对的集合 - 在Parent
的同时将这些对分组,而只使用父对,而不是整对。