ThenBy

In this chapter you will learn:

  1. How to use ThenBy operator
  2. Concatenate two ThenBy operators
  3. ThenBy by custom Comparer

Get to know ThenBy operator

using System;//from  j a v  a2s  .co  m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] names = { "Java", "C#", "Javascript", "SQL", 
              "Oracle", "Python", "C++", "C", "HTML", "CSS" };


        IEnumerable<string> query = names.OrderBy(s => s.Length).ThenBy(s => s);

        foreach (String s in query)
        {
           Console.WriteLine(s);
        }
    }
}

The output:

Concatenate two ThenBy operators

The following sorts first by length, then by the second character, and finally by the first character.

using System;//from   ja  v  a 2  s . c  o m
using System.Collections;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        string[] names = { "Java", "C#", "Javascript", "SQL", 
                "Oracle", "Python", "C++", "C", "HTML", "CSS" };

        names.OrderBy(s => s.Length).ThenBy(s => s[1]).ThenBy(s => s[0]);

        foreach (String s in names)
        {
           Console.WriteLine(s);
        }
    }
}

The output:

ThenBy by custom Comparer

Using an OrderBy and a ThenBy clause with a custom comparer to sort first by word length and then by a case-insensitive descending sort of the words in an array.

using System;//from   ja v  a2 s  .c om
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class CaseInsensitiveComparer : IComparer<string> {
    public int Compare(string x, string y) {
        return string.Compare(x, y, true);
    }
}

public class MainClass {
    public static void Main() {

        string[] words = { "a", "A", "b", "B", "C", "c" };

        var sortedWords =
            words.OrderBy(a => a.Length)
                    .ThenBy(a => a, new CaseInsensitiveComparer());

        foreach (var s in sortedWords) {
            Console.WriteLine(s);
        }
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use ThenByDescending operator
  2. ThenByDescending with custom Comparer
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip