I have a question about IGrouping and Select() method.
Lets say I've got 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 values (List<smth>
) from IGrouping<int, smth>
in such context?
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();
foreach (var v in structure)
{
var group = groups.Single(g => g.Key == v. ??? );
v.ListOfSmth = group.ToList();
}
First you need to select the desired group. Then you can use the ToList
method of on the group. The IGrouping
is a IEnumerable
of the values.
From definition of IGrouping :
IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable
you can just iterate through elements like this:
IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}
More clarified version of above answers:
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;
}
}
来源:https://stackoverflow.com/questions/8521025/how-to-get-values-from-igrouping