Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/apache-spark/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在c中返回Min谓词中的对象?_C# - Fatal编程技术网

C# 如何在c中返回Min谓词中的对象?

C# 如何在c中返回Min谓词中的对象?,c#,C#,在c语言中,我有以下代码 Pixel topLeft = potentialTopLeft.Min(p => p.GetX()); 它获取列表potentialTopLeft中最小的像素对象,但用于比较像素值的是GetX类方法的值。但问题是,它返回最小的GetX的值,我想要具有最小GetX的像素对象。有人知道如何修复它吗?应用排序,然后从IOrderedList中获取第一个元素: 您不需要对整个列表进行排序就可以找到具有minimun X的像素,这将增加代码的复杂性。您可以简单地使用:

在c语言中,我有以下代码

Pixel topLeft = potentialTopLeft.Min(p => p.GetX());
它获取列表potentialTopLeft中最小的像素对象,但用于比较像素值的是GetX类方法的值。但问题是,它返回最小的GetX的值,我想要具有最小GetX的像素对象。有人知道如何修复它吗?

应用排序,然后从IOrderedList中获取第一个元素:


您不需要对整个列表进行排序就可以找到具有minimun X的像素,这将增加代码的复杂性。您可以简单地使用:

var minX = potentialTopLeft.Min(p => p.GetX());
Pixel topLeft = potentialTopLeft.First(p => p.GetX() == minX);

或者,您可以让Pixel实现IComparable,并提供一个快速比较方法实现,如下所示:

class Pixel : IComparable<Pixel>
{
    public int X { get; set; }

    int IComparable<Pixel>.CompareTo(Pixel other)
    {
        if (other.X > this.X) { return -1; }
        else if (other.X == this.X) { return 0; }
        else {return 1; }
    }
}

这种方法的好处是,它使调用代码更具可读性,如果代码中有其他地方需要比较像素实例,您可以使用它。

您的potentialTopLeft是什么的集合?它的什么属性保存像素?它们是列表中的像素对象OK..那么你应该得到具有最小GetX值的像素对象。那么你还想要什么呢?它不是像我说的那样返回一个像素对象,而是返回一个整型的getX值。OrderByAscending没有一个方法,但是降序有一个方法。@omega,是的,动态写的:如果两个像素对象具有相同的minx值呢?Y值可能不同,并且First不一定返回与Min语句中查询的对象相同的对象。@Saragis然后可以使用。Wherep=>p.GetX==minX获取具有Min X的所有对象,并根据需要从该列表中选择所需对象。尽管如此,他不需要对整个列表进行排序。@Saragis,但这实际上并不重要,因为没有回退标准来处理重复的情况。另一个答案也只是选择一个GetX最低的,但没有特定的顺序。
class Pixel : IComparable<Pixel>
{
    public int X { get; set; }

    int IComparable<Pixel>.CompareTo(Pixel other)
    {
        if (other.X > this.X) { return -1; }
        else if (other.X == this.X) { return 0; }
        else {return 1; }
    }
}
Pixel topLeft = potentialTopLeft.Min();