fearofawhackplanet
fearofawhackplanet

Reputation: 53396

Get "Value" property in IGrouping

I have a data structure like

public DespatchGroup(DateTime despatchDate, List<Products> products);

And I am trying to do...

var list = new List<DespatchGroup>();

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!

Upvotes: 195

Views: 156303

Answers (4)

Bassl Kokash
Bassl Kokash

Reputation: 647

For any selected group,you could call

var selectedGroupValues=selectedGroup.SelectMany(x=>x);

Upvotes: 42

Rob H
Rob H

Reputation: 1849

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!

Upvotes: 28

LukeH
LukeH

Reputation: 269428

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());

Upvotes: 46

Marc Gravell
Marc Gravell

Reputation: 1062965

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());

Upvotes: 221

Related Questions