Linq:GroupBy的child.value属性值

时间:2016-12-13 10:33:23

标签: c# .net linq group-by

我的课程Parent包含Child个对象的集合,其中Child有两个属性:KeyValue

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" }
        }
    }
};

任何方法?

2 个答案:

答案 0 :(得分:3)

这对你有用吗?

var query =
    from p in parents
    from c in p.Children
    group p by c.Value;

这给出了:

query

您也可以使用:

var query =
    parents
        .SelectMany(p => p.Children, (p, c) => new { p, c })
        .GroupBy(x => x.c.Value, x => x.p);

这是一个即使Childrennull或空可枚举的查询:

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的同时将这些对分组,而只使用父对,而不是整对。