Amokrane Chentir
Amokrane Chentir

Reputation: 30385

Sorting a collection in alphabetical order

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

Thanks

Upvotes: 5

Views: 19142

Answers (5)

thecoop
thecoop

Reputation: 46098

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);

Upvotes: 12

mint
mint

Reputation: 3433

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).

Upvotes: 1

theburningmonk
theburningmonk

Reputation: 16051

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

Upvotes: 3

Toby
Toby

Reputation: 7544

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.

Upvotes: 1

Wil P
Wil P

Reputation: 3371

You can use a SortedList.

Upvotes: 4

Related Questions