c# - 使用 LINQ 对字符串数组进行排序

标签 c# asp.net linq

我有一个字符串数组声明如下

string[][] data = new string[3][];
string[] name = new string[10];
string[] contact = new string[10];
string[] address = new string[10];

填完name, address, contact后,有些数据地址可以为空字符串。之后我将它分配给字符串数组数据。

data[0] = name;
data[1] = contact;
data[2] = address

我如何使用 LINQ 按名称对字符串数组进行排序。我试试 data = data.orderby(y => y[0]).ToArray();

但是这种排序会改变字符串数组的顺序。假设data[0]是店名,排序后变成店地址。
任何人都知道如何对记录进行排序?请帮忙

最佳答案

您可以使用它对名称数组(存储在 data[0] 中)进行排序:

data[0] = data[0].OrderBy(x => x).ToArray();

但是,这将导致存储在其他数组中的数据与名称数组失去任何有意义的相关性(例如 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; }
}

要声明数组,请使用:

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));

第二个选项更有效,因为它会重新排列元素,并且不需要分配新数组来存储结果。

或者,使用 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 相似的性能方法,但是,如果您需要能够动态地添加或删除列表中的元素,这是一个更好的选择。

关于c# - 使用 LINQ 对字符串数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18951687/

相关文章:

c# - IIS 上的网站速度极慢

c# - 获取由 javascript 更改的文本框的值

c# - NHibernate Linq 和 DistinctRootEntity

c# - 我如何将 linq 转换为 lambda

linq - 如何将 DataTable 转换为 IEnumerable<Dictionary<string, object>>?

c# - 在 Code.cs 和 Code.cs[design] 中正确地从 Windows 窗体中删除一个项目

c# - 如何在 ViewModel 类中执行 ComboboxSelectionChanged 方法

c# - Linq 是否根据实际集合类型优化执行?

c# - 跳过WebForm中SqlDataSource中sql参数的设置值

c# - 有没有更好的搜索方法而不是 string.Contains ("keyword") 使用 asp.net?