Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order List<T> by enum

Tags:

c#

This is driving me nuts but it must be so simple.

I've got a class, the value of Strength can be HIGH/MEDIUM/LOW:-

public class SearchResults
{
    private List<string> _categories;
    public string caseID { get; private set; }
    ...
    public string Strength { get; set; }
}

I do an API call and get a List<SearchResults>

var resultres = JsonConvert.DeserializeObject<List<SearchResults>>(mycase.GetResults());

What I'm trying to do is to order resultres in the order HIGH/MEDIUM/LOW but if I do the following it goes by alphabetic i.e. H/L/M

resultres.Sort((x, y) => x.matchStrength.CompareTo(y.matchStrength));

I've (probably incorrectly) tried to use an enum: -

enum ResultStrength
{
    HIGH,
    MEDIUM,
    LOW
}

but I can't find a way to use it to force the order, if I use the following then it gives me a "Cannot convert lambda expression to type 'System.Collections.Generic.IComparer' because it is not a delegate type"

resultres.Sort((x, y) => x.ResultStrength.CompareTo(y.ResultStrength));

I've tried implementing various IComparer<SearchResults> and Comparison<SearchResults> but I just can't get it to compile and/or work properly.

like image 238
DrDan Avatar asked Jan 31 '26 14:01

DrDan


2 Answers

If you can modify SearchResults class, then just change Strength property from string type to type of ResultStrength enum. JSON.NET is smart enough to create enum value from string name.

public ResultStrength Strength { get; set; }

Sorting will be simple:

resultres.OrderBy(r => r.Strength)

NOTE: If you don't provide values to enum members, by default they will get following values:

enum ResultStrength
{
    HIGH = 0,
    MEDIUM = 1,
    LOW = 2
}

So HIGH will go before LOW. If you want to reverse order, you can use OrderByDescending


Otherwise you can sort by enum value parsed from Strenth string:

resultres.OrderBy(r => (int)Enum.Parse(typeof(ResultStrength),r.Strength))
like image 159
Sergey Berezovskiy Avatar answered Feb 03 '26 05:02

Sergey Berezovskiy


Just convert it to integer:

resultres.Sort((x, y) => ((int)x.ResultStrength).CompareTo((int)y.ResultStrength));
like image 43
eocron Avatar answered Feb 03 '26 05:02

eocron