LINQ查询(Group BY)?

时间:2011-02-07 06:56:45

标签: c# linq

考虑以下对象:

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

如果我有一个地址列表,我将如何使用LINQ获取城市,州和国家匹配的计数列表。

所以我的结果看起来像这样:

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

谢谢!

4 个答案:

答案 0 :(得分:9)

比Marc的回答更进了一步(在我发布之前他编辑了!)。 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(),
          };

答案 1 :(得分:2)

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

然后你可以做(​​例如):

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 :(得分:1)

这是我尝试的(在LINQPAD中)并且效果很好(类似于Enigmativity'答案):

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

输出:

ny cy india 2

by cy india 1

ny fr india 1

答案 3 :(得分:0)

在本文中了解LINQ中的分组 - http://www.devart.com/linqconnect/docs/querysamples.html。它对你有用。