DrDan
DrDan

Reputation: 63

Order List<T> by enum

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.

Upvotes: 3

Views: 1948

Answers (4)

Ghasan غسان
Ghasan غسان

Reputation: 5857

There is no need to use enum, you can make use of element's index in a reference list to order an unordered list properly.

var ReferenceList = new List<string>() { "Low", "Medium", "High" };
var unorderedList = new List<string>() { "Low", "High", "Low", "Medium", "High" };

// Now we order unorderedList by using element's position in the ReferenceList.
unorderedList.Sort((a, b) => ReferenceList.IndexOf(a).CompareTo(ReferenceList.IndexOf(b)));

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

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

Upvotes: 2

I.G. Pascual
I.G. Pascual

Reputation: 5965

Have you tried giving the enums names a value?

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

Then you could just follow @eocron's answer

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

Upvotes: 0

eocron
eocron

Reputation: 7526

Just convert it to integer:

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

Upvotes: 1

Related Questions