Coder Perfect

What is the best way to get values from IGrouping?

Problem

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

Assume I have an IEnumerableIGroupingint, smth>> as follows:

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

List is a Listsmth>, where list is a Listsmth>.

Now I need to find a mechanism to transmit the values of each IGrouping to another list:

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

Is there a way to extract the values (Listsmth>) from an IGroupingint, smth> in this situation?

Asked by Illia Ratkevych

Solution #1

Because IGroupingTKey, TElement> implements IEnumerableTElement>, you can use SelectMany to combine all of the IEnumerables into one:

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 of a program that compiles and runs: https://dotnetfiddle.net/DyuaaP

https://youtu.be/6BsU1n1KTdo provides a video commentary on this solution.

Answered by Matt Smith

Solution #2

foreach (var v in structure) 
{     
    var group = groups.Single(g => g.Key == v. ??? );
    v.ListOfSmth = group.ToList();
}

You must first choose the desired group. The ToList method on the group can then be used. The values are organised into an IEnumerable by the IGrouping.

Answered by Tim Cools

Solution #3

Versions of the answers above that have been clarified:

IEnumerable<IGrouping<int, ClassA>> groups = list.GroupBy(x => x.PropertyIntOfClassA);

foreach (var groupingByClassA in groups)
{
    int propertyIntOfClassA = groupingByClassA.Key;

    //iterating through values
    foreach (var classA in groupingByClassA)
    {
        int key = classA.PropertyIntOfClassA;
    }
}

Answered by Bronek

Solution #4

IGrouping is defined as follows:

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

You may just iterate over the following elements:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

Answered by user1275513

Solution #5

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

Because “IGroupingint, smth> group” is an IEnumerable with a key, you have two options:

foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Answered by SA-

Post is based on https://stackoverflow.com/questions/8521025/how-to-get-values-from-igrouping