Sorting an array of strings in C #

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

+3
source share
4 answers

You can sort the array using.

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

This will return the instance Ienumerable. If you need to save it as an array, use this code.

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

I'm not sure what you mean when you say that you need to implement some interfaces, but you do not need to do this when using IEnumerable.OrderBy. Just pass Func<TSource, TKey>in a lambda expression.

+6
source

OrderBywill not sort the existing array in place. If you need to do this, use Array.Sort.

OrderBy - , , Øyvind.

+2

Array.Sort(theArray).

: - , string ; ( ) IComparable/IComparable<T>, . IComparer/IComparer<T>, ( ) , .

+2

Linq () .

1:

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

-, , s => s.

2:

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

SQL , , , Linq.

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

0
source

Source: https://habr.com/ru/post/1785371/


All Articles