我有一张满是地址的桌子。我的目标是找到具有相似地址的人,并将他们组合在一起。当然,我可以这样做:
var groups = addresses.GroupBy(a => a.FullAddress);
哪个好。但是,用户可以选择要在GroupBy中应用的地址属性。例如:
//user selected postalCode & state
var groups = addresses.GroupBy(a => new { a.PostalCode, a.State });
用户可以将6个布尔值整合到他们的搜索中。有没有一种简单的方法通过LINQ来解决这个问题?如果没有,我确信我可以敲除一些if语句,但我想象有一个更优雅的解决方案,我无法找到任何类似的问题。
这是在ASP.NET MVC项目中,作为使用实体框架为报告页面构建AddressGroupsViewModel
的服务的一部分。
public AddressGroupsViewModel GetSearchResults(bool address1, bool address2, bool city, bool state, bool country, bool postalcode)
{
}
解
鉴于已接受的答案(几乎是我所需要的),我创建了满足我要求的查询:
var groups = dbContext
.GroupBy(t => new
{
Address1 = (address1 ? t.AddressLine1 : ""),
Address2 = (address2 ? t.AddressLine2 : ""),
City = (city ? t.City : ""),
State = (state ? t.State : ""),
Country = (country ? t.Country : ""),
PostalCode = (postalcode ? t.PostalCode : "")
});
答案 0 :(得分:1)
public AddressGroupsViewModel GetSearchResults(bool address1, bool address2, bool city, bool state, bool country, bool postalcode)
{
var result = from t in tableName
group t by new {
FieldA = (address1 ? "" : t.Address1),
FieldB = (address2 ? "" : t.Address2),
FieldC = (city ? "" : t.City),
FieldD = (state ? "" : t.State),
FieldE = (country ? "" : t.Country),
FieldF = (postalcode ? "" : t.PostalCode)
} into g
select g;
......
}