Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Query (Group BY)?

Tags:

c#

linq

Consider the following object:

public class Address { public string city; public string state; public string country; }

If I have a list of addresses how would I use LINQ to get a list of counts where the city, state, and country match.

So my result might look something like this:

  • "princeton" "nj" "usa" 122
  • "austin" "tx" "usa" 44
  • "la" "ca" "usa" 1
  • "princton" "na" "uk" 3
  • ....

Thanks!

like image 879
Luke Belbina Avatar asked Aug 31 '25 22:08

Luke Belbina


1 Answers

Went one step further than Marc's answer (which he edited before I posted!). LOL

var qry = from addr in addresses
          group addr by new { addr.city, addr.state, addr.country } into grp
          select new
          {
            city = grp.Key.city,
            state = grp.Key.state,
            country = grp.Key.country,
            count = grp.Count(),
          };
like image 80
Enigmativity Avatar answered Sep 03 '25 13:09

Enigmativity