繁体   English   中英

如何使用Linq表达式获得按两个字段排序的最大项目?

[英]How to get the maximum item ordered by two fields using a Linq expression?

是否有可能将result1作为单个linq表达式获得? 我知道这可能不是最佳做法,但出于好奇,我只想知道如何做。

result2有不同的答案,但它也正确。 但是,与O(N)相比,它具有O(NlogN)的复杂度。

void Main()
{
    A[] a = new A[4]{new A(0,0,0),new A(1,1,0),new A(1,2,1),new A(1,2,0)};
    /*
    //Grossly inefficient: replaced
    var tmpList = a.Where(x => (x.one == a.Max(y => y.one)));       
    var result1 = tmpList.First(x => (x.two == tmpList.Max(y => y.two)));
    */
    var maxOneValue = a.Max(x => x.one);
    var tmpList = a.Where(x => (x.one == maxOneValue));
    var maxTwoValueOfTmpList = tmpList.Max(x => x.two);
    var result1 = tmpList.First(x => (x.two == maxTwoValueOfTmpList));
    //A: 1, 2, 1

    var result2 = a.OrderBy(x => x.one)
              .ThenBy(x => x.two)
              .Last();
    //A: 1, 2, 0
}

class A 
{
    public int one;
    public int two;
    public int three;
    public A(int one, int two, int three)
    {
        this.one = one;
        this.two = two;
        this.three = three;
    }
}

编辑:我已经按问题编辑过,因此某些答案可能不正确。

一种方法是在您的A类上实现IComparable<A> 然后您的解决方案就变成了:

var result1 = a.Max(); // 1,2,1

这是实现IComparable<A>

class A : IComparable<A>
{
    ...

    public int CompareTo(A other)
    {

        return this.one == other.one ? this.two - other.two : this.one - other.one;
    }
}

这是一个演示: http : //ideone.com/ufIcgf 这样做的好处是它仍然具有O(N)的复杂度,并且也很简洁。

也许这可以解决您的问题:

a.OrderBy(x => x.one + x.two).Last()

该查询给出相同的结果:

var result = a.OrderByDescending(x => x.one + x.two)
                      .First();

但是随后您可能会获得没有最大“一”字段的项目。这应该可以:

var result = a.OrderByDescending(x => x.two)
               .Where(x => (x.one == a.Max(y => y.one)))
               .First();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM