I have a list of ingredients with the name of ingredient and the corresponding values. which I want to sort depending on a pre defined order.
List<Ingredients> frmltnIngredientsList = new List<Ingredients>
The list can have as many as 10 records. The first four records should be in the order of:
and the rest of them can be in any order
You could do something like this:
frmltnIngredientsList.OrderBy(item =>
item.Name == "Protein" ? 1 :
item.Name == "oil" ? 2 :
item.Name == "Fibre" ? 3 :
item.Name == "Ash" ? 4 :
5);
The OrderBy call will yield an IOrderedEnumerable<Ingredient>. So you need to assign that to a variable,
var orderedList = frmltnIngredientsList.OrderBy(item => ...);
... or call ToList() to be able to assign it to your variable of List<Ingredient> type:
frmltnIngredientsList = frmltnIngredientsList.OrderBy(item => ...).ToList();
It could of course be tidied up a bit. Either you could have a SortOrder property on your Ingredient list and just run .OrderBy(x => x.SortOrder), or you could at least move the logic out of sight:
public static class IngredientExtensions
{
public static int GetSortNumber(this Ingredient item) {
return item.Name == "Protein" ? 1 :
item.Name == "oil" ? 2 :
item.Name == "Fibre" ? 3 :
item.Name == "Ash" ? 4 :
5;
}
}
...
var orderedList = frmltnIngredientsList.OrderBy(item => item.GetSortNumber());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With