Question

I have a LINQ query that returns a list of states and a count of each state abbreviation occurrence from a datatable.

var query = ds.Tables[0].AsEnumerable()
            .GroupBy(r => r.Field<string>("state"))
            .Select(grp => new 
                            { 
                                state = grp.Key, 
                                Count = grp.Count()
                            })
            .OrderBy(o => o.state)
            .ToList();

It returns

State   Count
AL       55
AK       40
AZ       2

How would I modify this query to return an additional field (state name)? Or do I need to take another approach to accomplish this?

State  Name       Count
AL     Alaska     55
AK     Arkansas   40
AZ     Arizona    2
Was it helpful?

Solution

Create an anonymous type to group on:

var query = ds.Tables[0].AsEnumerable()
            .GroupBy(r => new
            {
                state = r.Field<string>("state"),
                name = r.Field<string>("name"),
            })
            .Select(grp => new
            {
                name = grp.Key.name,
                state = grp.Key.state,
                Count = grp.Count()
            })
            .OrderBy(o => o.state)
            .ToList();

OTHER TIPS

Assuming the "name" is the same for all "state" values you could just change your Select to:

        .Select(grp => new 
                        { 
                            state = grp.Key, 
                            Name = grp.First().Field<string>("State Name"),
                            Count = grp.Count()
                        })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top