Mike Darrow
Mike Darrow

Reputation: 15

Sorting an ArrayList

Based on my previous question, I've trying now to have them 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

Upvotes: 0

Views: 584

Answers (2)

digEmAll
digEmAll

Reputation: 57210

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 :)

Upvotes: 3

sehe
sehe

Reputation: 392921

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

Upvotes: 0

Related Questions