Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a list manually C#?

Tags:

c#

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:

  • Protein
  • oil
  • Fibre
  • Ash

and the rest of them can be in any order

like image 331
sony Avatar asked Feb 15 '26 13:02

sony


1 Answers

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());
like image 136
David Hedlund Avatar answered Feb 18 '26 01:02

David Hedlund



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!