LINQ query (BY group)?

Consider the following object:

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

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

So my result might look something like this:

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

Thank!

+3
source share
4 answers

One step further than Mark'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(),
          };
+9
source
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());
}

. .Key new { addr.city, addr.state, addr.country}, IEnumerable<Address>. , , :

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

( n + 1).

+2

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; }

Conclusion:

ny cy india 2

by cy india 1

ny fr india 1

+1
source

Read about grouping in LINQ in this article - http://www.devart.com/linqconnect/docs/querysamples.html . This may be helpful for you.

0
source

Source: https://habr.com/ru/post/1790390/


All Articles