-1

If I want to order a list based on more than one property, I can't see a good way of doing that other than forming those properties to numbers and then using OrderBy, for instance:

int someArbitraryNumber = 1000;

List<Tuple<int, int>> test = new List<Tuple<int, int>>() {
  new Tuple<int, int>(1, 3),
  new Tuple<int, int>(1, 4),
  new Tuple<int, int>(1, 5),
  new Tuple<int, int>(2, 3),
  new Tuple<int, int>(9, 15)
};

var orderedTest = test
  .OrderBy(x => x.Item1 + x.Item2 * someArbitraryNumber);

Here I'd be looking to for the resulting list to be:

    (1, 3),
    (2, 3),
    (1, 4),
    (1, 5),
    (9, 15)

That is to say, first ordered by the second item, then by the first.

OliverRadini
  • 6,238
  • 1
  • 21
  • 46
  • 1
    maybe a sample list of input and required output would help, `ThenBy` and `ThenByDescending` may do the trick - `var orderedTest = test.OrderBy(x => x.Item1).ThenBy(x => x.Item2);` or `var orderedTest1 = test.OrderBy(x => x.Item1).ThenByDescending(x => x.Item2);` – Dawood Awan Jun 07 '19 at 13:43
  • @DawoodAwan Thanks, `ThenBy` is exactly what I needed, and I've now added some example output – OliverRadini Jun 07 '19 at 14:21

1 Answers1

1

Use ThenBy():

int someArbitraryNumber = 10000; // Not used anymore

List<Tuple<int, int>> test = new List<Tuple<int, int>>() {
  new Tuple<int, int>(1, 3),
  new Tuple<int, int>(1, 4),
  new Tuple<int, int>(1, 5),
  new Tuple<int, int>(2, 3),
  new Tuple<int, int>(9, 15)
};

var orderedTest = test.OrderBy(x => x.Item2).ThenBy(x => x.Item1);

Other improvments

  • Use var if the type of a variable can be figured out by the compiler
  • Use ValueTuples, it's less verbose ((int, int) instead of Tuple<int, int>) and you can use names for the items
var test = new List<(int first, int second)>()
{
    (1, 3), (1, 4), (1, 5), (2, 3), (9, 15)
};

var orderedTest = test.OrderBy(x => x.second).ThenBy(x => x.first);
Emaro
  • 1,397
  • 1
  • 12
  • 21