Search code examples
c#linqsorting

Sort the list based on multiple numeric condition using LINQ


I want to sort a list based on 3 numeric conditions. I need to do this sorting based on the property called 'CompletionPercentage'. So the list should be sorted on below conditions

  1. Filter the list where the percentage should be greater than 0 and less than 100
  2. Next filter the list where the percentage is equal to 0
  3. Next filter the list where the percentage is equal to 100

I have tried the below code but it is not working. Please help.

var data = myCollection
  .ToList()
  .Where(x => getCourses.CourseLevel.Contains(x.CourseLevel)
  .OrderBy(x => x.CompletionPercentage > 1 && x.CompletionPercentage < 99)
  .ThenBy(x => x.CompletionPercentage == 0)
  .ThenBy(x => x.CompletionPercentage == 100);

Solution

  • I suggest mapping items into three groups as it's mentioned in the question:

    .OrderBy(item => item.CompletionPercentage ==   0 ? 2
                   : item.CompletionPercentage == 100 ? 3
                   : 1)
    

    Here we have running item (CompletionPercentage > 0 and CompletionPercentage < 100) be the 1st, then not started items (CompletionPercentage == 0) followed by completed items (CompletionPercentage == 100)

    Code:

    var data = myCollection
      .Where(item => getCourses.CourseLevel.Contains(item.CourseLevel)
      .OrderBy(item => item.CompletionPercentage ==   0 ? 2
                     : item.CompletionPercentage == 100 ? 3
                     : 1)
      .ThenBy(item => item.CompletionPercentage) // if you want order per cents as well 
      .ToList();            // if you want data to be List<T>