3

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

4 Answers 4

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

@aharon: It's the lambda expression's parameter. If you're going to learn LINQ, you'll need to learn about various features from C# 3.
Nit: you don't pass a Predicate<T> into OrderBy - you pass a Func<TSource, TKey>.
Whoops. A type there. Fixed it now. A predicate would obviously not help in orderby. Thanks Jon and Mark.
3

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

2

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

0

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.

2 Comments

what type is the unsorted? I tried with string[], not working... ?
string[] test = new[] { "3", "1", "c"}; should work without problems. You need to include namespace System.Linq

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.