问题描述
我有一个字符串数组声明如下
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
我怎么可以按名称使用LINQ字符串数组排序。我试着
。数据= data.orderby(Y => Y [0])ToArray的();
How I can sort the string array by name using LINQ. I try data = data.orderby(y => y[0]).ToArray();
但这种将改变字符串数组的顺序。假设数据[0]是商店的名字,但它的排序成为存储地址之后。结果
任何一个有想法,我怎么可以排序的记录?请帮助
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
推荐答案
您可以使用此名称数组进行排序(存储在数据[0]
):
You can use this to sort the name array (which is stored at data[0]
):
data[0] = data[0].OrderBy(x => x).ToArray();
然而,这将导致存储在其他阵列中的数据,以松名数组任何有意义的相关性(如名称[3]
很可能不会匹配接触[3]
)。为了避免这种情况,
我强烈建议使用一个类来存储这些信息:
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:
class MyClass // TODO: come up with a better name
{
public string Name { get; set; }
public string Contact { get; set; }
public string Address { get; set; }
}
要声明数组,使用:
MyClass[] data = new MyClass[10];
data[0] = new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
};
和对数组进行排序:
data = data.OrderBy(x => x.Name).ToArray();
或者这样:
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<MyClass> data = new List<MyClass>(10);
data.Add(new MyClass // Populate first record
{
Name = "...",
Contact = "...",
Address = "...",
});
和对列表进行排序:
data.Sort((x, y) => x.Name.CompareTo(y.Name));
这将有类似表现的的Array.Sort
的方法,但是,它是一个更好的选择,如果你需要能够从你的列表中添加或删除元素动态。
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.
这篇关于使用LINQ排序字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!