开发者

Get "Value" property in IGrouping

开发者 https://www.devze.com 2023-02-06 16:05 出处:网络
I have a data structure like public DespatchGroup(DateTime despatchDate, List<Products> products);

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!

0

精彩评论

暂无评论...
验证码 换一张
取 消