【问题标题】:Group with linq on multiple properties via grouping method通过分组方法在多个属性上使用 linq 分组
【发布时间】:2019-07-31 20:05:14
【问题描述】:

我有以下代码:

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

【问题讨论】:

    标签: c# linq grouping


    【解决方案1】:

    数组是引用类型,所以当分组方法比较两个具有相同值的数组时,不能确定它们是否相同,因为引用不同。你可以阅读更多here

    一种解决方案是考虑一个类而不是使用数组作为函数的结果,并使用另一个类来比较实现 IEqualityComparer 接口的结果,并将其传递给 GroupBy 方法,以便分组方法可以找到哪些组合ZipCode 和 State 真的是等价的。 read more

    【讨论】:

      【解决方案2】:

      不确定这是否可行,因为我无法复制您的代码。
      但是在进行分组之前,在单独的变量中添加组键和字符串 [] 可能会更容易。像这样。

      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 on complex object (e.g. List<T>)

      【讨论】:

        猜你喜欢
        • 2014-01-02
        • 1970-01-01
        • 2017-11-17
        • 1970-01-01
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多