(流利)linq组由强类型

时间:2017-05-24 13:47:36

标签: c# linq

我没有得到这个,也许有人会照亮我。 这有效:

var grouped = getRuntimeParams(sheet, pcode)
  .GroupBy(x => new { 
     dbTable = x.dbTable, 
     dbIndexField = x.dbIndexField, 
     dbIndex = x.dbIndex });

这意味着我按行应该将行分组。 这不是,这意味着结果是"分组"逐行:

var grouped = getRuntimeParams(sheet, pcode)
  .GroupBy(x => new ParamGroup { 
     dbTable = x.dbTable, 
     dbIndexField = x.dbIndexField, 
     dbIndex = x.dbIndex });

但我需要将结果组传递给方法,因此我需要强类型化。当然,ParamGroup类是公共的,可以在这里看到公共属性。 我究竟做错了什么? 谢谢。

2 个答案:

答案 0 :(得分:3)

您必须覆盖 ParamGroupEquals以及GetHashCode方法,如下所示:

public class ParamGroup {

  ... 

  public override bool Equals(Object o) {
    ParamGroup other = o as ParamGroup;

    if (null == other)
      return false;

    return dbTable == other.dbTable &&
           dbIndexField == other.dbIndexField &&
           dbIndex == other.dbIndex;
  }

  public override int GetHashCode() {
    return (dbIndexField == null ? 0 : dbIndexField.GetHashCode()) ^
            dbIndex ^
           (dbTable == null ? 0 : dbTable.GetHashCode());
  }
}

不当行为的原因是未覆盖时 ParamGroup使用默认 Equals实施(来自Object)进行比较引用,而非实例的字段/属性,因此所有实例都不同(不相等)。

匿名类型(在您的第一个示例中)覆盖这些方法:

https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/anonymous-types

答案 1 :(得分:2)

第一个查询有效且第二个查询单独放入一个组的事实只指向一件事:ParamGroup没有Equals和{{1}的正确实现}。

如果这是您的课程,实施这些方法将解决问题。否则,您需要使用带有equality comparer的重载。