开发者

Sorting an ArrayList

开发者 https://www.devze.com 2023-02-21 22:57 出处:网络
Based on my previous question, I\'ve trying now to have t开发者_高级运维hem in the following order using the same approach, OrderByDescending and ThenBy

Based on my previous question, I've trying now to have t开发者_高级运维hem in the following order using the same approach, OrderByDescending and ThenBy

Original (can be in any random order):

1:1
0:0
0:1
2:1
1:0
2:0

Output

2:0 
1:0 
0:0 
2:1 
1:1 
0:1

as you can see, a is descending, and b being ascending. But I'm still not getting the right sort. Any ideas why? Thanks


Think to what you would do manually:

  1. First you must sort the values by the 2nd part in ascending order
  2. Then you must sort values having the same 2nd part, using the 1st part in descending order

Translated in LINQ it's pretty the same:

var sorted = arrayList
.Cast<string>()
.Select(x => x.Split(':'))
.OrderBy(x => x[1])
.ThenByDescending(x => x[0])
.Select(x => x[0] + ":" + x[1]);

To clarify a bit more, ThenBy/ThenByDescending methods are used to sort elements that are equal in the previous OrderBy/OrderByDescending, hence the code :)


arrayList.ToList().Select(i => { var split = i.Split(":".ToArray(),2));
                                return new { a = Int32.Parse(split[0]),
                                             b = Int32.Parse(split[1}) }; 
                               })
.OrderByDescending(i => i.a)
.ThenBy(i => i.b)

From your question it is not clear whether you want the order-by's reversed (just swap them). Work from there, perhaps rejoining

.Select(i => String.Format("{0}:{1}", i.a, i.b));

Good luck

0

精彩评论

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