aharon
aharon

Reputation: 7633

Sort an array of strings in C#

How can I sort an array of strings using the OrderBy function? I saw I need to implement some interfaces...

Upvotes: 3

Views: 5178

Answers (4)

hwcverwe
hwcverwe

Reputation: 5367

Linq has two (syntax) ways to sort an array of strings.

1:

string[] sortedStrings = unsortedStrings.OrderBy(s => s).ToArray();

This syntax is using a Lambda Expressions if you don't know what s => s means.

2:

sortedStrings = (from strings in unsortedStrings  
                 orderby strings  
                 select strings).ToArray();

This example looks a bit like a SQL statement and is probably easier to read if you are new with Linq.

ToArray() converts the IOrderedEnumerable<string> to as string[] in this case.

Upvotes: 0

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

Reputation: 60694

You can sort the array by using.

var sortedstrings = myStringArray.OrderBy( s => s );

This will return an instance of Ienumerable. If you need to retain it as a array, use this code instead.

myStringArray = myStringArray.OrderBy( s => s ).ToArray();

I'm not sure what you are referring to when you said that you have to implement some interfaces, but you do not have to do this when using the IEnumerable.OrderBy. Simply pass a Func<TSource, TKey> in the form of a lambda-expression.

Upvotes: 7

Marc Gravell
Marc Gravell

Reputation: 1062600

To sort inside an existing array, call Array.Sort(theArray).

Re your comment on interfaces: you don't need to add any interfaces here, since string is well supported; but for custom types (of your own) you can implement IComparable / IComparable<T> to enable sorting. You can also do the same passing in an IComparer / IComparer<T>, if you want (or need) the code that provides the ordering to be separate to the type itself.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500055

OrderBy won't sort the existing array in place. If you need to do that, use Array.Sort.

OrderBy always returns a new sequence - which of course you can convert to an array and store a reference to in the original variable, as per Øyvind's answer.

Upvotes: 3

Related Questions