How do I iterate an IGrouping<T> Interface?
Ive got ths really annoying issue I have grouped a set of data and I cant get to the data within the group. I can get to the key bit not the data..
I have a load of data that is in the form
Data.Period = x
Data.Adjustment = y
I perform a GroupBy
var groupedData = Data.GroupBy(x => x.Period new {x.Period});
This brings back (according to linq) my hierarchical data which is starting to look how I want it. Id like to iterate through the contents but cant...How do I do this? and how do I...
Work how to get to the Data.Adjustment without using a projection. And I dont want to project yet because I have to perform another grouping....help! :-)
Solution 1:
The IGrouping<TKey, TElement>
interface inherits IEnumerable<TElement>
:
foreach (var group in groupedData)
{
var groupKey = group.Key;
foreach (var groupedItem in group)
DoSomethingWith(groupKey, groupedItem);
}
I note that you will be better off using this for your query, however:
var groupedData = Data.GroupBy(x => x.Period);
rather than this:
var groupedData = Data.GroupBy(x => new {x.Period});
If, for example, you wanted to average the adjustments, you could do this:
foreach (var group in groupedData)
Console.WriteLine("Period: {0}; average adjustment: {1}", group.Key, group.Average(i => i.Adjustment));
Solution 2:
Each element of a sequence of IGrouping<TKey, TElement>
is an IEnumerable<TElement>
that you can iterate over to get the data that has a common TKey
:
var groups = Data.GroupBy(x => x.Period);
foreach(var group in groups) {
Console.WriteLine("Period: {0}", group.Key);
foreach(var item in group) {
Console.WriteLine("Adjustment: {0}", item.Adjustment);
}
}
So in the above, groups
is an IEnumerable<IGrouping<TPeriod, TAdjustment>>
where TPeriod
is the type of Period
(you didn't tell us) and TAdjustment
is the type of Adjustment
. Then, group
is an object that implements IEnumerable<TAdjustment>
(but it also has a Key
property so that you can get the key. Finally, item
is a TAdjustment
, and for each group
, all the item
that come from iterating over that group
have the same key.
Solution 3:
Though maybe obvious for others one can also use:
var groups = Data.GroupBy(x => x.Period);
foreach(var group in groups)
{
List<Data> dataListByPeriod = group.ToList();
//use this list
}
Solution 4:
Just use foreach
:
foreach(var group in groupedData)
{
Console.WriteLine("Period: {0}", group.Key);
foreach(var item in group)
Console.WriteLine(" Adjustment: {0}", item.Adjustment);
}