从清单中获得3件物品的最大值

时间:2019-05-22 14:51:28

标签: c#

我有问题。 我创建了一个看起来像这样的列表:

public class SelectedTriangleRegistryObject
{
    public float x1 { get; set; }
    public float y1 { get; set; }
    public float x2 { get; set; }
    public float y2 { get; set; }
    public float x3 { get; set; }
    public float y3 { get; set; }
    public int TriangleNum { get; set; }
    public int SequenceNum { get; set; }
}

现在,我想选择x坐标的最大值。因此,最大的数字可能是x1,x2或x3。只是3中的最高值。我该怎么做?

我知道这一行:

float XMaxShapeValue = triangles.Max(x => x.x3);

但是知道我想要这样的东西:

float XMaxShapeValue = triangles.Max(x => x.x1, x.x2, x.x3);

我该怎么做?

示例:

x1的值为[2,4,5]
x2的值为[2,5,3]
x3的值为[4,6,1]

那我想得到数字6。但是你不知道哪个x的数字最大!

2 个答案:

答案 0 :(得分:0)

将注释中的建议应用于对LINQ查询使用两个Math.Max语句:

float XMaxShapeValue = triangles.Max(t => Math.Max(t.x1, Math.Max(t.x2, t.x3)));

这将返回最大值X的float值,无论它是x1x2还是x3。这将不会返回实际具有最大X值的三角形对象。

答案 1 :(得分:0)

要在浮点数组中找到最大值:

float[] x1 = {1, 2, 3};
float[] x2 = {2, 3, 4};
float[] x3 = {3, 4, 5};

float max(float[]...floatArrays) {
    max = Float.MIN;
    foreach (float[] floats in floatArrays) {
        foreach (f in floats) {
            max = Math.Max(float, max);
        }
    }
    return max;
}

我不太了解这个问题,但以您的示例为例,这就是您想要的。