Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq Order By Contains List

Tags:

c#

sql

linq

I have a List of ints that model.SelectedIngredients and in this example the list contains the values [15128, 4593,15046,]. I use this list then as a filter in my Linq query as follows:

List<INGREDIENT> selectedIngredients = db.INGREDIENT.Where(i => model.SelectedIngredients.Contains(i.IngredientId)).ToList();

However, this sorts the results by IngredientId ascending as default[4593,15046,15128].

What I would like is to get the selectedIngredients back in the same order as they are in model.SelectedIngredients.

I know I could do it in a for loop but I just wondered if there was a way I could do it within the Linq query?

Thanks

like image 669
rory Avatar asked Jan 28 '26 05:01

rory


1 Answers

You can acomplish this quite easy by using the index of your list with ids.

List<INGREDIENT> selectedIngredients = db.INGREDIENT
                         .Where(i => model.SelectedIngredients.Contains(i.IngredientId))
                         .AsEnumerable()
                         .OrderBy(i => model.SelectedIngredients.IndexOf(i.IngredientId))
                         .ToList();
like image 137
Simon Karlsson Avatar answered Jan 30 '26 20:01

Simon Karlsson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!