Bird
Raised Fist0
C Sharp (C#)programming~20 mins

OrderBy and sorting in C Sharp (C#) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
OrderBy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this OrderBy example?
Consider the following C# code that sorts a list of integers using OrderBy. What will be printed to the console?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        List<int> numbers = new() { 5, 3, 8, 1 };
        var sorted = numbers.OrderBy(n => n);
        foreach(var num in sorted) {
            Console.Write(num + " ");
        }
    }
}
A1 3 5 8
B8 5 3 1
C5 3 8 1
D3 5 1 8
Attempts:
2 left
💡 Hint
OrderBy sorts elements in ascending order by default.
Predict Output
intermediate
2:00remaining
What is the output when sorting strings by length?
This code sorts a list of strings by their length using OrderBy. What will be printed?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        List<string> words = new() { "apple", "dog", "banana", "cat" };
        var sorted = words.OrderBy(w => w.Length);
        foreach(var w in sorted) {
            Console.Write(w + " ");
        }
    }
}
Acat dog apple banana
Bapple dog banana cat
Cbanana apple dog cat
Ddog cat apple banana
Attempts:
2 left
💡 Hint
OrderBy sorts by the key selector, here the string length.
Predict Output
advanced
2:00remaining
What is the output of this OrderByDescending with complex objects?
Given this code that sorts a list of Person objects by Age descending, what will be printed?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

record Person(string Name, int Age);

class Program {
    static void Main() {
        List<Person> people = new() {
            new("Alice", 30),
            new("Bob", 25),
            new("Charlie", 35)
        };
        var sorted = people.OrderByDescending(p => p.Age);
        foreach(var p in sorted) {
            Console.Write(p.Name + " ");
        }
    }
}
ACharlie Bob Alice
BCharlie Alice Bob
CBob Alice Charlie
DAlice Bob Charlie
Attempts:
2 left
💡 Hint
OrderByDescending sorts from largest to smallest by the key.
Predict Output
advanced
2:00remaining
What is the output of this chained OrderBy and ThenBy?
This code sorts a list of tuples first by the first item ascending, then by the second item descending. What is printed?
C Sharp (C#)
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
    static void Main() {
        var list = new List<(int, int)>{ (1, 2), (1, 3), (2, 1), (2, 2) };
        var sorted = list.OrderBy(x => x.Item1).ThenByDescending(x => x.Item2);
        foreach(var t in sorted) {
            Console.Write($"({t.Item1},{t.Item2}) ");
        }
    }
}
A(1,3) (1,2) (2,2) (2,1)
B(1,2) (1,3) (2,1) (2,2)
C(2,2) (2,1) (1,3) (1,2)
D(2,1) (2,2) (1,2) (1,3)
Attempts:
2 left
💡 Hint
OrderBy sorts by first item ascending, ThenByDescending sorts by second item descending within groups.
🧠 Conceptual
expert
2:00remaining
Which option causes a runtime error when sorting with OrderBy?
Given a list of objects, which code snippet will cause a runtime exception when using OrderBy in C#?
Alist.OrderBy(x => x.GetHashCode())
Blist.OrderBy(x => x.PropertyThatExists)
Clist.OrderBy(x => x.NonExistentProperty)
Dlist.OrderBy(x => x.ToString())
Attempts:
2 left
💡 Hint
Accessing a property that does not exist will cause an error at runtime.

Practice

(1/5)
1. What does the OrderBy method do in C#?
easy
A. Sorts a collection in ascending order based on a key
B. Deletes elements from a list
C. Reverses the order of elements in a list
D. Filters elements based on a condition

Solution

  1. Step 1: Understand the purpose of OrderBy

    The OrderBy method sorts elements in a collection based on a key in ascending order.
  2. Step 2: Compare with other options

    Options B, C, and D describe different operations (deletion, reversing, filtering) which OrderBy does not perform.
  3. Final Answer:

    Sorts a collection in ascending order based on a key -> Option A
  4. Quick Check:

    OrderBy = Sort ascending [OK]
Hint: OrderBy sorts ascending by key, not filtering or deleting [OK]
Common Mistakes:
  • Confusing OrderBy with filtering methods like Where
  • Thinking OrderBy modifies the original list
  • Mixing up OrderBy with reversing or deleting
2. Which of the following is the correct syntax to sort a list of integers named numbers in ascending order using OrderBy?
easy
A. numbers.OrderBy();
B. numbers.OrderBy(n);
C. numbers.OrderBy(n => n);
D. numbers.OrderBy(n => );

Solution

  1. Step 1: Check the correct lambda syntax

    OrderBy requires a key selector function like n => n to specify sorting key.
  2. Step 2: Validate each option

    numbers.OrderBy(n => n); uses correct lambda syntax. numbers.OrderBy(); misses the key selector. numbers.OrderBy(n); passes a variable, not a lambda. numbers.OrderBy(n => ); has incomplete lambda syntax.
  3. Final Answer:

    numbers.OrderBy(n => n); -> Option C
  4. Quick Check:

    OrderBy needs a key selector lambda [OK]
Hint: OrderBy always needs a key selector lambda like n => n [OK]
Common Mistakes:
  • Omitting the lambda expression inside OrderBy
  • Passing a variable instead of a lambda
  • Using incomplete or invalid lambda syntax
3. What will be the output of the following code?
var fruits = new List<string> { "banana", "apple", "cherry" };
var sorted = fruits.OrderBy(f => f);
foreach(var fruit in sorted) {
    Console.Write(fruit + " ");
}
medium
A. banana apple cherry
B. apple banana cherry
C. cherry banana apple
D. apple cherry banana

Solution

  1. Step 1: Understand the sorting key

    The code sorts the list of fruits alphabetically by their string value.
  2. Step 2: Determine the sorted order

    Alphabetically, "apple" comes before "banana", which comes before "cherry".
  3. Final Answer:

    apple banana cherry -> Option B
  4. Quick Check:

    OrderBy sorts strings alphabetically [OK]
Hint: OrderBy sorts strings alphabetically ascending [OK]
Common Mistakes:
  • Assuming original order is preserved
  • Confusing OrderBy with OrderByDescending
  • Not recognizing alphabetical order
4. The following code throws a compile-time error. What is the mistake?
var numbers = new List<int> { 3, 1, 2 };
var sorted = numbers.OrderBy();
medium
A. numbers must be an array, not a list
B. List<int> cannot be sorted
C. OrderBy should be OrderByDescending
D. OrderBy requires a key selector lambda expression

Solution

  1. Step 1: Identify the method signature requirement

    OrderBy requires a key selector function to specify how to sort elements.
  2. Step 2: Analyze the error cause

    Calling OrderBy() without any argument causes a compile error because the key selector is missing.
  3. Final Answer:

    OrderBy requires a key selector lambda expression -> Option D
  4. Quick Check:

    OrderBy needs a lambda key selector [OK]
Hint: Always provide a key selector lambda to OrderBy [OK]
Common Mistakes:
  • Calling OrderBy without arguments
  • Thinking OrderBy works without a key selector
  • Confusing List and array types for sorting
5. Given a list of students with properties Name and Score, how do you sort the list first by Score descending, then by Name ascending using LINQ?
hard
A. students.OrderByDescending(s => s.Score).ThenBy(s => s.Name);
B. students.OrderBy(s => s.Score).OrderBy(s => s.Name);
C. students.OrderBy(s => s.Name).OrderByDescending(s => s.Score);
D. students.OrderByDescending(s => s.Name).ThenByDescending(s => s.Score);

Solution

  1. Step 1: Understand multi-level sorting

    To sort by multiple keys, use OrderBy or OrderByDescending for the first key, then ThenBy or ThenByDescending for the next keys.
  2. Step 2: Apply correct order and directions

    We want to sort by Score descending first, then by Name ascending, so use OrderByDescending(s => s.Score) followed by ThenBy(s => s.Name).
  3. Final Answer:

    students.OrderByDescending(s => s.Score).ThenBy(s => s.Name); -> Option A
  4. Quick Check:

    OrderByDescending + ThenBy for multi-level sort [OK]
Hint: Use ThenBy after OrderBy for secondary sorting [OK]
Common Mistakes:
  • Using multiple OrderBy calls instead of ThenBy
  • Mixing ascending and descending incorrectly
  • Sorting by wrong property order