Nil Pun
Nil Pun

Reputation: 17383

Generate Orinal Number in LINQ

I've a List that contains a records below:

name:apple
category:fruit

name:choysum
category:vegetable

name:chicken
category: poultry

name: lamb
category: meat

...

I need to order this list by category below:

vegetable
fruit
poultry
meat..

Could someone please help me how above is possible using LINQ. I'm thinking of creating a another property called ordinal and tag as 1,2,3,4 for above categories. Then order by ordinal.

Upvotes: 0

Views: 97

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503869

Yes, you could do something like:

var orderedCategories = new List<string> { "fruit", "vegetable", "poulty", "meat" };
var ordered = list.OrderBy(x => orderedCategories.IndexOf(x.Category))
                  .ToList();

If you have lot of categories, you might want to use a Dictionary<string, int> (or a Dictionary<Category, int> if you have a separate class for categories).

Upvotes: 4

Related Questions