C# 使用 LINQ 对字符串数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18951687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort string array using LINQ
提问by Bubble Bub
I has a string array declare as below
我有一个字符串数组声明如下
string[][] data = new string[3][];
string[] name = new string[10];
string[] contact = new string[10];
string[] address = new string[10];
After i fill the data to name, address and contact, the address can be empty string in some data. After that I assign it to string array data.
在我填写姓名、地址和联系人的数据后,地址在某些数据中可以为空字符串。之后我将它分配给字符串数组数据。
data[0] = name;
data[1] = contact;
data[2] = address
How I can sort the string array by name using LINQ. I try data = data.orderby(y => y[0]).ToArray();
如何使用 LINQ 按名称对字符串数组进行排序。我尝试 data = data.orderby(y => y[0]).ToArray();
but this sort will change the sequence of the string array. Suppose data[0] is store name but after sorting it become store address.
Any one has idea how can I sort the record? Please help
但是这种排序会改变字符串数组的顺序。假设 data[0] 是商店名称,但排序后成为商店地址。
任何人都知道如何对记录进行排序?请帮忙
回答by p.s.w.g
You can use this to sort the name array (which is stored at data[0]
):
您可以使用它对名称数组(存储在data[0]
)进行排序:
data[0] = data[0].OrderBy(x => x).ToArray();
However, this will cause the data stored in the other arrays to loose any meaningful correlation to the name array (e.g. name[3]
most likely will not match up with contact[3]
). To avoid this,
I'd strongly recommend using a class to store this information:
然而,这将导致存储在其他数组中的数据失去与名称数组的任何有意义的相关性(例如,name[3]
很可能与 不匹配contact[3]
)。为了避免这种情况,我强烈建议使用一个类来存储这些信息:
class MyClass // TODO: come up with a better name
{
public string Name { get; set; }
public string Contact { get; set; }
public string Address { get; set; }
}
To declare the array, use:
要声明数组,请使用:
MyClass[] data = new MyClass[10];
data[0] = new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
};
And to sort the array:
并对数组进行排序:
data = data.OrderBy(x => x.Name).ToArray();
Or this:
或这个:
Array.Sort(data, (x, y) => x.Name.CompareTo(y.Name));
The second option is more efficient as it rearranges the elements in place, and doesn't require allocating a new array to store the results.
第二个选项更有效,因为它重新排列元素,并且不需要分配新数组来存储结果。
Or alternatively, use a List<T>
:
或者,使用一个List<T>
:
List<MyClass> data = new List<MyClass>(10);
data.Add(new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
});
And to sort the list:
并对列表进行排序:
data.Sort((x, y) => x.Name.CompareTo(y.Name));
This will have similar performance to the Array.Sort
method, however, it is a much better option if you need to be able to add or remove elements from your list dynamically.
这将具有与该Array.Sort
方法相似的性能,但是,如果您需要能够动态地从列表中添加或删除元素,它是一个更好的选择。