Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get values out of IGrouping?

Tags:

c#

linq

igrouping

I have applied IGrouping<> over a list - here's what it looks like:

IEnumerable<IGrouping<TierRequest,PingtreeNode>> Tiers
{
    get { return ActiveNodes.GroupBy(x => new TierRequest(x.TierID, x.TierTimeout, x.TierMaxRequests)); }
}

Later in my code I iterate over Tiers. Its simple to get the key data using the Key element, but how do I get the IEnumerable<PingtreeNode> that forms the value part?

Thanks in advance

like image 381
dotnetnoob Avatar asked Nov 19 '13 13:11

dotnetnoob


3 Answers

Tiers.Select(group => group.Select(element => ...));

like image 198
Vladimir Avatar answered Nov 07 '22 05:11

Vladimir


in foreach you can get values like this

foreach(var group in tiers)
{
    TierRequest key = group.Key;
    PingtreeNode[] values = group.ToArray();
}
like image 31
maxlego Avatar answered Nov 07 '22 06:11

maxlego


The group itself implements IEnumerable<T> and can be iterated over, or used with linq methods.

var firstGroup = Tiers.First();

foreach(var item in firstGroup)
{
  item.DoSomething();
}

// or using linq:
firstGroup.Select(item => item.ToString());

// or if you want to iterate over all items at once (kind of unwinds
// the grouping):
var itemNames = Tiers.SelectMany(g => g.ToString()).ToList();
like image 4
Anders Abel Avatar answered Nov 07 '22 07:11

Anders Abel