sort string array using LINQ

40,715

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.

Share:
40,715

Related videos on Youtube

Bubble Bub
Author by

Bubble Bub

Updated on July 18, 2022

Comments

  • Bubble Bub
    Bubble Bub almost 2 years

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

    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

    • Serguei Fedorov
      Serguei Fedorov over 10 years
      This seems a bit complex for such a simple thing. Simply create a class/struct to hold your data and create an array out of that. It is far easier to sort and handle.

Related