开发者

Sorting by two columns with LINQ (Edited). Forget it! I'll post the answer to make things clear

Hi I have a list that looks like this:

      val1   val2
r1     10     3              
r2      5     5
开发者_JS百科r3      9     7
r4      4     1
r5      2     9
r6     1000   0

I need to get the row in which both values are at their maximum together for example:

      val1   val2
r1     10     3      no match both values can be highe
r2      5     5      no match both values can be higher
r3      9     7      MATCH val1 can be higher but it would make val2 lower and viceversa
r4      4     1      no match both values can be higher
r5      2     9      no match val2 is at its highest but val1 can be higher
r6     1000   0      no match val1 is at its highest but val2 can be higher

in this case it would be r3

hope this time it's clear


It's not clear what you're asking for:

1) you don't want any pair that is dominated by another pair.
2) you don't want items where val1 is at maximum but val2 could be higher, and vice versa.

1 implies that you want some pair on the upper edge of the set.
2 simply means you discard the two endpoints.

this still leaves any possible number of choices

alt text http://img341.imageshack.us/img341/1720/chartgn.png

In the above graph, there are 2 points that are strictly dominated, and so you disqualify them. There are two points that satisfy (X is maximum but Y can increase, or vice versa) so you disqualify those as well. That still leaves two points that satisfy (Neither x nor Y can increase without lowering the other one)

In fact (as also pointed out by Jason in comments), looking at your original data, (10,3) also satisfies (neither val1 nor val2 can be increased without lowering the other)


      val1   val2   val1+val2
r1     10     3        13
r2      5     5        10
r3      9     7        16    <<
r4      4     1         5
r5      2     9        11

Looks like the best solution is still to select the maximum by the sum of the two numbers:

Tuple<int,int> GetBest(IEnumerable<Tuple<int,int>> pairs)
{
    return pairs.MaxBy(pair => pair.Item1 + pair.Item2);
}

(with MaxBy from MoreLINQ)


Just select the cell the highest sum of those two columns.


here:

given

     val1  val2
r1  10    3
r2  5     5
r3  9     7
r4  4     1
r5  2     9
r6  1000  0
r7  5     1000
r8  5     4

order by val2 ASC

     val1  val2
r6  1000  0
r4  4     1
r1  10    3
r8  5     4
r2  5     5
r3  9     7
r5  2     9
r7  5     1000

then order by val1 DESC

     val1  val2
r6  1000  0
r1  10    3
r3  9     7
r7  5     1000
r2  5     5
r8  5     4
r4  4     1
r5  2     9 

now do s=(val1[n+1]-val1[n])/(val2[n+1]-val2[n])

n       s
1   -330
2   -0.25
3   1.333333333
4   0
5   0
6   0.001001001
7   -0.25
8   0.222222222

here, we can see that s is greater at n=3 which corresponds to r3(9,7)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜