sort string array using LINQ

前端 未结 1 1102
礼貌的吻别
礼貌的吻别 2021-01-13 02:12

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          


        
相关标签:
1条回答
  • 2021-01-13 02:54

    You can use this to sort the name array (which is stored at 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:

    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<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.

    0 讨论(0)
提交回复
热议问题