c# - How to get the maximum item ordered by two fields using a Linq expression? -
is possible result1 single linq expression? understand may not best practise know how out of curiousity.
result2 has different answer correct too. however, has complexity of o(nlogn) opposed o(n).
void main() { 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 { 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; } }
edit: have edited question , hence answers may not tally.
this query gives same result :
var result = a.orderbydescending(x => x.one + x.two) .first();
but items without max 'one' field.. 1 should work :
var result = a.orderbydescending(x => x.two) .where(x => (x.one == a.max(y => y.one))) .first();
Comments
Post a Comment