OrderBy
In this chapter you will learn:
- How to use OrderBy operator
- How to sort string array by word length
- Case-insensitive sort
- 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:
Home » C# Tutorial » Linq Operators