C# LINQ查询(分组依据)?
考虑以下对象:C# LINQ查询(分组依据)?,c#,linq,C#,Linq,考虑以下对象: public class Address { public string city; public string state; public string country; } 如果我有一个地址列表,我将如何使用LINQ获得城市、州和国家匹配的计数列表 所以我的结果可能是这样的: “普林斯顿”“新泽西”“美国”122 美国德克萨斯州奥斯汀44 “la”“ca”“usa”1 “普林斯顿”“北美”“英国”3 谢谢 var qry = addresses.GroupBy(add
public class Address { public string city; public string state; public string country; }
如果我有一个地址列表,我将如何使用LINQ获得城市、州和国家匹配的计数列表
所以我的结果可能是这样的:
- “普林斯顿”“新泽西”“美国”122
- 美国德克萨斯州奥斯汀44
- “la”“ca”“usa”1
- “普林斯顿”“北美”“英国”3
var qry = addresses.GroupBy(addr => new { addr.city, addr.state, addr.country});
然后您可以执行(例如):
i、 e.每个组的.Key
是复合新{addr.city,addr.state,addr.country}
,每个组也是IEnumerable
。请注意,对于数据库查询,您应该提前告诉它您的全部意图,例如:
foreach(var row in qry) {
Console.WriteLine("{0} {1} {2} \t {3}",
row.Key.city, row.Key.state, row.Key.country, row.Count());
}
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)。比Marc的答案(他在我发布之前编辑过!)更进一步。哈哈 这是我(在LINQPAD中)尝试过的,效果很好(类似于Enigmativity的答案):
void Main()
{
List lst=新列表();
lst.Add(新地址{city=“ny”、state=“cy”、country=“india”});
lst.Add(新地址{city=“ny”、state=“cy”、country=“india”});
lst.Add(新地址{city=“by”,state=“cy”,country=“india”});
lst.Add(新地址{city=“ny”、state=“fr”、country=“india”});
var qry=来自lst中的地址
按新{addr.city,addr.state,addr.country}将addr分组到grp中
选择新的
{
城市=grp.Key.city,
state=grp.Key.state,
国家=grp.Key.country,
count=grp.count(),
};
qry.Dump();
}
公共类地址{public string city;public string state;public string country;}
输出:
ny cy india 2
by cy india 1
ny fr india 1
ny cy印度2
由西印度1
ny fr印度1
阅读本文中关于LINQ分组的内容-。它可能对你有用
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