I have a data structure like
public DespatchGroup(DateTime despatchDate, List<Products> products);
And I am trying to do...
var list = new List<DespatchGrou开发者_运维技巧p>();
foreach (var group in dc.GetDespatchedProducts().GroupBy(i => i.DespatchDate))
{
// group.Values is not correct... how do I write this?
list.Add(new DespatchGroup(group.Key, group.Values);
}
I'm obviously not understanding IGrouping
as I can't see how to actually get to the data records within the group!
The group implements IEnumerable<T>
- In the general case, just call foreach
over the group
. In this case, since you need a List<T>
:
list.Add(new DespatchGroup(group.Key, group.ToList());
There's no Values
property or similar because the IGrouping<T>
itself is the IEnumerable<T>
sequence of values. All you need to do in this case is convert that sequence to a list:
list.Add(new DespatchGroup(group.Key, group.ToList());
For any selected group,you could call
var selectedGroupValues=selectedGroup.SelectMany(x=>x);
Just a related tip - since, as the other answers have said, the grouping is an IEnumerable, if you need to access a specific index you can use group.ElementAt(i)
.
This is probably obvious to a lot of people but hopefully it will help a few!
精彩评论