How to group by custom types with linq

后端 未结 2 491
余生分开走
余生分开走 2021-01-04 10:48

I have this class

public class Item
{
       public Coordinate coordinate { get; set; }
        ...
        ...
}

With Coordinate being def

相关标签:
2条回答
  • 2021-01-04 11:16

    You've shown the Equals implementation, but not GetHashCode. You need to override both (and in a consistent way) for grouping to work.

    Sample GetHashCode implementation:

    public override int GetHashCode()
    {
        int hash = 23;
        hash = hash * 31 + Latitude.GetHashCode();
        hash = hash * 31 + Longitude.GetHashCode();
        return hash;
    }
    

    Note that comparing float values for exact equality is always somewhat risky - but I'd at least expect your unit tests to pass, given that they're not performing any calculations.

    0 讨论(0)
  • 2021-01-04 11:28

    There is an overload to the GrouBy method that takes an IEqualityComparer as a parameter, but is there the equivalent using the group clause?

    You can always group by an anonymous type, if you just want a quick inline solution and aren't worried about hitting the exact type for the keys:

    var grouped =
      from it in items 
      group it by new {it.Coordinate.Latitude, it.Coordinate.Longitude};
    
    0 讨论(0)
提交回复
热议问题