简体   繁体   English

在C#中对字符串数组进行排序

[英]Sort an array of strings in C#

How can I sort an array of strings using the OrderBy function? 如何使用OrderBy函数对字符串数组进行排序? 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 . 这将返回一个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 . 当你说你必须实现一些接口时,我不确定你指的是什么,但是在使用IEnumerable.OrderBy时你不必这样做。 Simply pass a Func<TSource, TKey> in the form of a lambda-expression. 只需以lambda表达式的形式传递Func<TSource, TKey>

OrderBy won't sort the existing array in place. OrderBy不会对现有数组进行排序。 If you need to do that, use Array.Sort . 如果需要,请使用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. OrderBy总是返回一个序列 - 根据Øyvind的答案,当然你可以转换为数组并在原始变量中存储引用。

To sort inside an existing array, call Array.Sort(theArray) . 现有数组内部进行排序,请调用Array.Sort(theArray)

Re your comment on interfaces: you don't need to add any interfaces here, since string is well supported; 重新评论接口:你不需要在这里添加任何接口,因为string得到很好的支持; but for custom types (of your own) you can implement IComparable / IComparable<T> to enable sorting. 但对于自定义类型(您自己的),您可以实现IComparable / IComparable<T>以启用排序。 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. 可以在同一个传球IComparer / IComparer<T>如果你希望(或需要),提供了排序是不同的类型本身的代码。

Linq has two (syntax) ways to sort an array of strings. Linq有两种(语法)方法来对字符串数组进行排序。

1: 1:

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

This syntax is using a Lambda Expressions if you don't know what s => s means. 如果您不知道s => s含义,则此语法使用Lambda表达式

2: 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. 此示例看起来有点像SQL语句,如果您是Linq的新手,可能更容易阅读。

ToArray() converts the IOrderedEnumerable<string> to as string[] in this case. 在这种情况下, ToArray()IOrderedEnumerable<string>转换为string[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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