2

My class:

    public class Foo
    {
        public int A { get; set; }
        public List<Bar> Bars { get; set; }
    }

I've got IEnumerable<Foo>. I would like get List<Foo> grouping by A, and get Bars list, which contais all elements at Bars for group.

So final Foo.Bars should contains all elements of Bar at group

Is it possible with linq?

2
  • Aren't the Foos in your source IEnumerable<Foo> already that way? You source must be of a different type, right? What does the source actually look like? Commented Jun 15, 2012 at 13:12
  • No i would like get collection of the same type, but with merging lists Commented Jun 15, 2012 at 13:13

1 Answer 1

5
var result = foos.GroupBy(f => f.A)
                 .SelectMany(grp => grp.Select(f => f.Bars));

As Rawling has mentioned, this returns not an IEnumerable<Foo>, so try this:

IEnumerable<Foo> result = 
            foos.GroupBy(f => f.A)
            .Select(grp => new Foo() { 
                A = grp.Key,
                Bars = grp.SelectMany(ff => ff.Bars).Distinct().ToList()
            });

I'm not sure whether you want a distinct list of Bars or not. Note that you may need to override Equals and GetHashCode in class Bar.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems like what he might be looking for, but I'm still confused about the actual source.
This won't return a List<Foo>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.