6

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

2
  • 5
    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. Commented Sep 23, 2013 at 4:19
  • Use Data Array to List Commented Sep 23, 2013 at 4:26

1 Answer 1

28

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.