[英]Group with linq on multiple properties via grouping method
我有以下代码:
var linqResults = (from rst in QBModel.ResultsTable
group rst by GetGroupRepresentation(rst.CallerZipCode, rst.CallerState) into newGroup
select newGroup
).ToList();
使用分组方法:
private string[] GetGroupRepresentation(string ZipCode, string State)
{
string ZipResult;
if (string.IsNullOrEmpty(ZipCode) || ZipCode.Trim().Length < 3)
ZipResult = string.Empty;
else
ZipResult = ZipCode.Substring(0, 3);
return new string[]{ ZipResult, State };
}
这运行得很好,但根本不会分组。 QBModel.ResultsTable具有427条记录,并且在linq运行之后,linqResults仍然具有427条记录。在调试中,我可以看到相同的邮政编码和状态名相同的副本。 我猜想这与我从分组方法返回的数组有关。
我在这里做错了什么?
如果我在不使用数组的情况下将截断的邮政编码和州名的返回值连接起来,则会得到84个分组。
如果我除去rst.CallerState参数并将分组方法更改为:
private string GetGroupRepresentation(string ZipCode)
{
if (string.IsNullOrEmpty(ZipCode) || ZipCode.Trim().Length < 3)
return string.Empty;
return ZipCode.Substring(0, 3);
}
它会给我66个小组
我并不是很想连接组值,因为以后想单独使用它们,这是错误的,因为它基于数组是否起作用,但是,类似于以下内容:
List<DataSourceRecord> linqResults = (from rst in QBModel.ResultsTable
group rst by GetGroupRepresentation(rst.CallerZipCode, rst.CallerState) into newGroup
select new MapDataSourceRecord()
{
State = ToTitleCase(newGroup.Key[1]),
ZipCode = newGroup.Key[0],
Population = GetZipCode3Population(newGroup.Key[0])
}).ToList();
不知道这是否行得通,因为我无法复制您的代码。
但也许在进行分组之前,在单独的变量中添加组密钥和string []会更容易。 像这样。
var linqdatacleanup = QBModel.ResultsTable.Select(x=>
new {
value=x,
Representation = GetGroupRepresentation(rst.CallerZipCode, rst.CallerState),
GroupKey= GetGroupRepresentationKey(rst.CallerZipCode, rst.CallerState)
}).ToList();
因此GetGroupRepresentationKey返回单个字符串,而GetGroupRepresentation返回您的字符串[]
这样您就可以对该数据集进行分组,并根据需要访问数据。
但是在您花大量时间进行此检查之前,请先检查此堆栈溢出问题。 也许会帮助GroupBy处理复杂对象(例如List <T>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.