How to get values from IGrouping

Illia Ratkevych picture Illia Ratkevych · Dec 15, 2011 · Viewed 210.2k times · Source

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?

Answer

Matt Smith picture Matt Smith · Dec 15, 2011

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