How can I sort an array of strings using the OrderBy function? I saw I need to implement some interfaces...
4 Answers
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.
3 Comments
Predicate<T> into OrderBy - you pass a Func<TSource, TKey>.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.
Comments
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.
Comments
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.