Search code examples
c#linqselectigrouping

How to get values from IGrouping


I have a question about IGrouping and the Select() method.

Let's say I've got an IEnumerable<IGrouping<int, smth>> in this way:

var groups = list.GroupBy(x => x.ID);

where list is a List<smth>.

And now I need to pass values of each IGrouping to another list in some way:

foreach (var v in structure)
{
    v.ListOfSmth = groups.Select(...); // <- ???
}

Can anybody suggest how to get the values (List<smth>) from an IGrouping<int, smth> in such a context?


Solution

  • Since IGrouping<TKey, TElement> implements IEnumerable<TElement>, you can use SelectMany to put all the IEnumerables back into one IEnumerable all together:

    List<smth> list = new List<smth>();
    IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.id);
    IEnumerable<smth> smths = groups.SelectMany(group => group);
    List<smth> newList = smths.ToList();
    

    Here's an example that builds/runs: https://dotnetfiddle.net/DyuaaP

    Video commentary of this solution: https://youtu.be/6BsU1n1KTdo