4

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

Thanks

Amokrane Chentir
  • 29,280
  • 37
  • 112
  • 157

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
  • 44,124
  • 18
  • 127
  • 185
4

You can use a SortedList.

Wil P
  • 3,281
  • 1
  • 18
  • 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,283
  • 13
  • 58
  • 103
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,124
  • 3
  • 24
  • 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,233
  • 10
  • 37
  • 54