tags:

views:

65

answers:

2
class Car{
     int ID {get;set;}
     string Text {get;set;}
}

List<Car> allCars = new List<Car>(){ new Car{ ID = 1, Text = "one"}, new Car{ ID = 2, Text = "two"}, new Car{ ID = 3, Text = "three"}, new Car{ ID = 4, Text = "four"} };
int[] existingCarIds = new int[]{ 2, 4 };

I would like to have this list.

CarWithID2
CarWithID4
CarWithID1
CarWithID3

So I did:

List<Car> carList = allCars.Where(d => existingCarIds.Contains(d.ID)).Concat(allCars.Where(d => !existingCarIds.Contains(d.ID))).ToList();

Is there are any other way to do the same query?

Thanks

Lorenzo.

+1  A: 

You can use OrderBy:

List carList = allCars.OrderBy(d => !existingCarIds.Contains(d.ID)).ToList();
jdv
+1  A: 

Use OrderBy - at the very least, it will better show what is going on: reordering.

If you need to order the list in exactly the same order as the array, use

var reordered = allCars.OrderBy(car=>
    {
        var index = Array.IndexOf(existingCars, car.ID);
        return index<0 ? int.MaxValue : index; // put elements that don't have matching ID in the end
    });

This query orders by index in existingCars arrays, with elements that have no matching id in the array going last.

Nevermind