Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort two Lists<T> together as one?

Tags:

c#

asp.net

I have two List which I am accessing by index (e.g. Name[10], Date[10]). They're closely tied, so Name[10] is related to Date[10] and vice versa.

This design has worked well but now I need to sort them. I can sort them both individually but obviously that would remove the relationship between the two lists and make them worthless.

I thought about using a Dictionary<string, DateTime> instead but it seems I can only access that by Key (which is also unworkable). Essentially I need three things, two values and one index which I can iterate through numerically (not foreach).

Can anyone help? It seems I either need to change data-structure or work out how to sort two distinct List<T> together...

public class Results
{ 
public List<string> Name { get; set; }
public List<DateTime> Date{ get; set; }
}

for (int x = 0; x < results; x++)
{ z.N = results.Name[X]; z.D = results.Date[x]; } 
like image 784
user1102872 Avatar asked Dec 16 '11 23:12

user1102872


3 Answers

Use the Array.Sort overload that takes an array of keys and an array of values, it does precisely what you want. (This method has been available since .NET 2.0.)

like image 87
yoyo Avatar answered Nov 15 '22 17:11

yoyo


It sounds like you're fighting against doing the obvious solution which involves a little bit of upfront work: creating a type to encapsulate the name/date pair.

That's absolutely what you should do. Then you can have one list, sort it by name or by date or whatever you want, and you never need to worry about the two lists getting out of sync etc.

If your Results class doesn't do anything apart from contain those two lists, you can actually end up with the same number of types - you can ditch Results entirely, in favour of List<Result> where Result has a name and a date.

like image 30
Jon Skeet Avatar answered Nov 15 '22 16:11

Jon Skeet


Do yourself a favor and keep the two things together:

public class NameAndDate {
  public string Name { get; set; }
  public DateTime Date { get; set; }
}

Then you keep them in one list (List<NameAndDate>):

If you want to sort by the name, add a IComparer implementation to NameAndDate, then you can just call Sort() on the list.

If you want to keep access to the Name and the Date, add accessor methods to Results, like

public string GetName(int index) {
  return list[i].Name;
}
like image 28
flq Avatar answered Nov 15 '22 16:11

flq