prawn
prawn

Reputation: 2653

Linq Grouping items by property

I'm trying to group an object by one property (State). The end goal is to have a list. And within each list is an object consisting of two properties. I have data that looks like the following...

State      Name        ID
CA         John        12
CA         Kevin       13
CA         Joe         14
AZ         Sally       15754
AZ         Stuart      1263
TN         Sam         1211

How would one go about using linq to make this a list of object 'People' consisting of a person's name and ID grouped by state? This is what I've tried...but it's not working

var result = from groupOne in dataset
             group groupOne by OneGroup.State into g
             select new People() { People = g.ToList() }.ToList();

Upvotes: 0

Views: 147

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

Why are you grouping by OneGroup.State, when OneGroup is not a part of the query?

That one should do the trick:

var result = from groupOne in dataset
             group groupOne by groupOne.State into g
             select new {
                 State = g.Key,
                 People = g.Select(x => new { x.Name, x.ID })
             };

It returns anonymous types, but you can easily change it to return your class objects if you need.

Upvotes: 1

Related Questions