OrderBy

In this chapter you will learn:

  1. How to use OrderBy operator
  2. How to sort string array by word length
  3. Case-insensitive sort
  4. Sort with custom Comparer

Get to know OrderBy operator

The following query emits a sequence of names in alphabetical order:

using System;/* 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);
        foreach(String s in query){
           Console.WriteLine(s);
        }
    }
}

The output:

Sort by word length

The following codesorts names by length.

using System;/*from   j  av a2s  .  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" };

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

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

The output:

Case-insensitive sort

The following code performs a case-insensitive sort:

using System;//  j  a 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(n => n, StringComparer.CurrentCultureIgnoreCase);

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

The output:

Sort with custom Comparer

using System;//from  j  av  a  2s . c o  m
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, new CaseInsensitiveComparer());


    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use OrderByDescending operator
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