当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Linq: GroupBy its child.value property value

问题描述:

I have a class Parent with a collection of Child objects, where Child has two properties: Key and Value:

class Parent

{

public IEnumerable<Child> Children { get; set; }

}

class Child

{

public String Key { get; set; }

public String Value { get; set; }

}

I need to group a List<Parent> by its Child.Value.

Example:

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

}

}

};

Any approach?

网友答案:

Does this work for you?

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

This gives:


You can also use this:

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

This is a query that works even if Children is null or an empty enumerable:

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);
网友答案:

You can use chained Linq's SelectMany and GroupBy:

var result = parents
    .SelectMany(parent => parent.Children,
               (parent, child) => new { Key = child.Value, Parent = parent })
    .GroupBy(x => x.Key,
             x => x.Parent);

What it logically does is:

  • For each Child (using the flattening SelectMany) select the Child's value as a Key and its Parent
  • Now that you have a collection of Key-Parent pairs - group those by the Key while taking only the parent instead of the whole pair.
分享给朋友:
您可能感兴趣的文章:
随机阅读: