5

Is there any way, out of the box, to sort a collection in alphabetical order (using C# 2.0 ?).

Thanks

Amokrane Chentir
  • 29,907
  • 37
  • 114
  • 158

5 Answers5

12

What sort of collections are we talking about? A List<T>? ICollection<T>? Array? What is the type stored in the collection?

Assuming a List<string>, you can do this:

 List<string> str = new List<string>();
 // add strings to str

 str.Sort(StringComparer.CurrentCulture);
thecoop
  • 45,220
  • 19
  • 132
  • 189
4

You can use a SortedList.

Wil P
  • 3,341
  • 1
  • 20
  • 20
3

How about Array.Sort? Even if you don't supply a custom comparer, by default it'll sort the array in alphabetical order:

var array = new string[] { "d", "b" };

Array.Sort(array); // b, d
theburningmonk
  • 15,701
  • 14
  • 61
  • 104
1
List<string> stringList = new List<string>(theCollection);
stringList.Sort();

List<string> implements ICollection<string>, so you will still have all of the collection-centric functionality even after you convert to a list.

Toby
  • 7,354
  • 3
  • 25
  • 26
1

This may not be out of the box, but you can also use LinqBridge http://www.albahari.com/nutshell/linqbridge.aspx to do LINQ queries in 2.0 (Visual Studio 2008 is recommended though).

mint
  • 3,341
  • 11
  • 38
  • 55