score:9

Accepted answer

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

score:0

Read about grouping in LINQ in this article - http://www.devart.com/linqconnect/docs/querysamples.html. It can be useful for you.

score:1

This is what i tried(In LINQPAD) and it works well (Similar to Enigmativity' Answer ):

void Main()
{

    List<Address>   lst = new List<Address>();
    lst.Add(new Address{ city = "ny", state = "cy", country = "india"});
    lst.Add(new Address{ city = "ny", state = "cy", country = "india"});
    lst.Add(new Address{ city = "by", state = "cy", country = "india"});
    lst.Add(new Address{ city = "ny", state = "fr", country = "india"});
        var qry = from addr in lst
        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(),
        };
        qry.Dump();
}
public class Address { public string city; public string state; public string country; }

Output:

ny cy india 2

by cy india 1

ny fr india 1

score:2

var qry = addresses.GroupBy(addr => new { addr.city, addr.state, addr.country});

then you can do (for example):

foreach(var row in qry) {
    Console.WriteLine("{0} {1} {2} \t {3}",
                 row.Key.city, row.Key.state, row.Key.country, row.Count());
}

i.e. the .Key of each group is the composite new { addr.city, addr.state, addr.country}, and each group is also IEnumerable<Address>. Note that for database queries you should tell it your entire intent up front, for example:

var qry = from addr in db.Addresses
          group addr by new { addr.city, addr.state, addr.country} into grp
          select new {
              grp.Key.city, grp.Key.state,
              grp.Key.country, Count = grp.Count()
          };

so that it has the best possible chance to do a sensible query (not n+1).


Related Query