tags:

views:

119

answers:

5

Hi,

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

Thanks

+7  A: 

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
Refactor! (5 more to go..)
Filip Ekberg
I don't like using `var` in general situations
thecoop
+2  A: 

You can use a SortedList.

Wil P
Gah, got me by a minute.
Will
A: 
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
+2  A: 

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
A: 

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