简体   繁体   中英

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

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM