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.

2 Answers 2

12

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.

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

Comments

2

You can use OrderBy:

List carList = allCars.OrderBy(d => !existingCarIds.Contains(d.ID)).ToList();

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.