Sorting multiple arrays c#

戏子无情 提交于 2020-01-25 11:15:51

问题


currently I'm working on a project where i'm required to sort a total of 6 arrays.

I've managed to sort the arrays individually using a quicksort, however, I'm just wondering if there is a way to sort 1 array and reflect that on the order of elements in the other arrays. For example, if I sort my date array to an ascending order, I want the other arrays to still match up with the dates in respect to the new order.

If possible, could this still be done through a quick sort?


回答1:


Likely you have a setup something like this:

DateTime [] dates;
string [] names;
int [] ids;
//...etc

Consider instead to condense your data into a single object, then have a single array of that object:

public class MyObject 
{
    DateTime date { get; set; }
    string name { get; set; }
    int id { get; set; }
}

Now you will only have 1 array:

MyObject [] objects;

And you can sort the whole collection of objects by their date:

objects.Sort((a, b) => a.date.CompareTo(b.date));

Also consider using Lists rather than straight arrays, as the use case for using vanilla arrays in c# is very small:

List<MyObject> objects;



回答2:


I think the more appropriate option will be to create a new class with all different 6 kind of properties

public class myClass
{
    public DateTime date{get;set;}
    public string name{get;set;}
    //....
}

Then create a single array/list of that class.

public List<myClass> arrData;

Now you can sort that array based on any of your desired property and it will keep the order as per your requirements

arrData.OrderBy(x => x.name)

You can replace x.name with any of your myClass property.

This approach makes your code clean and easy to manage as well.




回答3:


It looks like LINQ uses the quick sort algorithm for the OrderBy method (see previous StackOverflow question).
Something like this should take care of it for you:

DateTime[] datesOfBirth = new DateTime[] { new DateTime(1955, 10, 28), new DateTime(1955, 2, 24) };
String[] firstNames = new String[] { "William", "Steve" };
String[] lastNames = new String[] { "Gates", "Jobs" };

var people = 
    datesOfBirth
    .Select((_, i) => new 
        { 
            DateOfBirth = datesOfBirth[i],
            FirstName = firstNames[i],
            LastName = lastNames[i]
        })
    .OrderBy(x => x.DateOfBirth)
    .ToArray();


来源:https://stackoverflow.com/questions/29591992/sorting-multiple-arrays-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!