c# how do i sort a group of lists

dal

dal

Associate
Joined
10 Sep 2005
Posts
905
Location
Lincolnshire
Hi all. I know this may not be the best way of doing this but I've got a small group of lists that represent aircraft data.
Which looks like this :

public List <string> AIRCRAFT_ID = new List<string>();
public List <int> ALTITUDE = new List<int>();
public List <int> passengers_on_board = new List<int> ();

So each element of the 3 lists represents one aircraft. This works fine when all I'm doing is adding aircraft to the list.

Now how would I get on if i wanted to sort the list based on say altitude because if I was to do something like :
ALTITUDE.sort .....

Then the other lists would be out of sync.

This is quite new to me so hopefully any help would be in laymans terms (if possible).

Regards
 
Class and linq.

public class Aircraft
{
public string AIRCRAFT_ID { get; set; }
public int ALTITUDE { get; set; }
public int passengers { get; set; }
}

var aircrafts = new List<Aircraft>();

aircrafts.Add(new Aircraft { AIRCRAFT_ID = "y", ALTITUDE = 1, passengers = 100 });
aircrafts.Add(new Aircraft { AIRCRAFT_ID = "a", ALTITUDE = 2, passengers = 200 });
aircrafts.Add(new Aircraft { AIRCRAFT_ID = "z", ALTITUDE = 2, passengers = 400 });

aircrafts = aircrafts.OrderBy(x => x.AIRCRAFT_ID).ToList();

Can also sort on multiple items.

aircrafts = aircrafts.OrderBy(x => x.AIRCRAFT_ID).ThenBy(x => x.passengers).ToList();
 
Class and linq.

public class Aircraft
{
public string AIRCRAFT_ID { get; set; }
public int ALTITUDE { get; set; }
public int passengers { get; set; }
}

var aircrafts = new List<Aircraft>();

aircrafts.Add(new Aircraft { AIRCRAFT_ID = "y", ALTITUDE = 1, passengers = 100 });
aircrafts.Add(new Aircraft { AIRCRAFT_ID = "a", ALTITUDE = 2, passengers = 200 });
aircrafts.Add(new Aircraft { AIRCRAFT_ID = "z", ALTITUDE = 2, passengers = 400 });

aircrafts = aircrafts.OrderBy(x => x.AIRCRAFT_ID).ToList();

Can also sort on multiple items.

aircrafts = aircrafts.OrderBy(x => x.AIRCRAFT_ID).ThenBy(x => x.passengers).ToList();

I've decided to go with this but how could I get the index of a certain record if I only had say the aircraft ID ?
Regards.
 
You can also just grab the whole class object with linq and access the relevant data that way.

var x = aircrafts.FirstOrDefault(a => a.AIRCRAFT_ID == "y");

can then do
x.ALTITUDE
or
x.passengers


also sort your variable names out :p
 
Back
Top Bottom