sony
sony

Reputation: 1503

Order a list manually 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:

and the rest of them can be in any order

Upvotes: 2

Views: 2717

Answers (1)

David Hedlund
David Hedlund

Reputation: 129782

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());

Upvotes: 14

Related Questions