Start learning free

LESSON 266 OF 674 · TUPLES, SORTING & BUILT-INS

Custom Sorting in C#

Lesson

TL ; DR:

LINQ sorts by your own rule. OrderBy takes a lambda that says what to sort each item by.


List<int> nums = new List<int>(new[] {25, 13, 5, 41, 33});

List<int> byLastDigit = nums.OrderBy(n => n % 10).ThenBy(n => n).ToList();
// 41 13 33 5 25

List<int> scores = new List<int>(new[] {70, 95, 82});

List<int> highFirst = scores.OrderByDescending(s => s).ToList();
// 95 82 70


Full lesson:

You met Sort() in the Shopping Cart project. It sorts a list from small to large, or from A to Z. Sometimes you need another order. The shortest word may have to come first, or the highest score.

LINQ has methods for that. You met LINQ and its lambdas with Where and Select. Here the lambda says what to sort each item by. The lambda w => w.Length sorts words by their length.

  • The method OrderBy(w => w.Length) sorts from small to large.
  • The method OrderByDescending(s => s) sorts from large to small.
  • The method ThenBy(n => n) adds a second rule. It only sorts items that tie on the first rule.
  • The method ThenByDescending is a second rule from large to small.

Above, OrderBy(n => n % 10) sorts the numbers by their last digit. Then ThenBy(n => n) puts numbers with the same last digit from small to large.

Don't call OrderBy twice. The second OrderBy sorts everything again and forgets the first rule. Use ThenBy for the second rule.

LINQ makes a new sequence and leaves the list as it was. End with ToList() to get a List back. The list's own Sort() changes the list itself instead.


Your task

A pet shop sells toys. Their prices are in prices. Make a List named highFirst with the prices from high to low.

The shop's pets are in names. Make a List named byLastLetter with the names sorted by their last letter, in alphabetical order. Names with the same last letter go from A to Z.

The code already prints both, one item per line.

Expected output:

30
12
8
5
Bella
Luna
Bo
Coco
Max
Rex
STEP 1 OF 2
    Ctrl + Enter to check