How to

sort collection

Published: 30. September 2011 | Updated: 30. September 2011
License: Microsoft Public License (MS-PL)
Categories: Collections
Tags: C# Collections
Was this snippet helpful for you? YESYES / NONO

Import namespace

using System.Linq;

Code

var collection = new[] {"c", "b", "a", "e", "d"};

var sorted = collection.OrderBy(i => i);

Console.WriteLine("Ascending:");
foreach (string s in sorted)
{
    Console.WriteLine(s);
}

var sortedDescending = collection.OrderByDescending(i => i);

Console.WriteLine("Descending:");
foreach (string s in sortedDescending)
{
    Console.WriteLine(s);
}
Console Output:
Ascending:
a
b
c
d
e
Descending:
e
d
c
b
a
Send us feedback about this snippet »



Related Snippets: