gpt4 book ai didi

.net - 如何使用 linq 按自定义类型分组

转载 作者:行者123 更新时间:2023-12-04 00:23:56 24 4
gpt4 key购买 nike

我有这个类

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

坐标定义如下:
public class Coordinate
{
public Coordinate(float latitude, float longitude)
{
Latitude = latitude;
Longitude = longitude;
}

public float Latitude { get; private set; }
public float Longitude { get; private set; }
}

我想要一个这样的 linq 查询:
var grouped = from it in items
group it by it.Coordinate into grp
select grp;

As mentioned here by MSDN我认为如果我在我的 Coordinate 类上覆盖 Equals,这是可能的:

Use a named type if you must pass the query variable to another method. Create a special class using auto-implemented properties for the keys, and then override the Equals and GetHashCode methods. You can also use a struct, in which case you do not strictly have to override those methods. For more information see How to: Implement an Immutable Class That Has Auto-Implemented Properties



等于 Coordinate 类的实现:
public override bool Equals(object obj)
{
var coord = obj as Coordinate;
if(coord == null) return false;
return (Latitude == coord.Latitude && Longitude == coord.Longitude);
}

我仍然无法让我的 linq 查询按相似的坐标进行分组,就像我的 失败 测试显示:
[TestMethod]
public void GroupBy_3ItemsWith2DifferentCoordinates_Returns2Groups()
{
var items = new List<Item>
{
new Item {Coordinate = new Coordinate(10, 10)},
new Item {Coordinate = new Coordinate(10, 10)},
new Item {Coordinate = new Coordinate(12, 10)},
};
var grouped = from it in items
group it by it.Coordinate into g
select g;
Assert.AreEqual(2, grouped.Count());
}

GrouBy 方法有一个重载,它将 IEqualityComparer 作为参数,但是否有使用 group 子句的等效项?
我做错了什么吗??有什么想法吗?

最佳答案

您已经展示了 Equals 实现,但没有展示 GetHashCode。您需要覆盖两者(并以一致的方式)以使分组工作。

示例 GetHashCode 实现:

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

注意比较 float完全相等的值总是有点风险 - 但我至少希望你的单元测试能够通过,因为它们没有执行任何计算。

关于.net - 如何使用 linq 按自定义类型分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2280183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com