gpt4 book ai didi

c# - 返回满足特定条件的列表元素

转载 作者:太空狗 更新时间:2023-10-29 22:36:45 24 4
gpt4 key购买 nike

我有一个类:

class Point
{
double X, Y;
}

来自List<Point> ,说我想要 Point其中 Point.X + Point.Y是列表中的最大值。我将如何在 LINQ 中执行此操作?

最佳答案

这将是一种方式(尽管无论如何都不是最佳方式):

List<Point> list = ...;
Point maxPoint = list.OrderByDescending(p => p.X + p.Y).First();

另一种应该表现更好的方法是修改你的 Point要实现的类 IComparable<T> ,像这样:

class Point : IComparable<Point>
{
double X, Y;

public int CompareTo(Point other)
{
return (X + Y).CompareTo(other.X + other.Y);
}
}

... 这样您就可以简单地执行以下操作:

List<Point> list = ...;
Point maxPoint = list.Max();

关于c# - 返回满足特定条件的列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396023/

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