Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Max() of alphanumeric value

Tags:

c#

.net

linq

max

I have a dictionary containg ID which are alphanumeric (e.g. a10a10 & d10a9) from which I want the biggest ID, meaning 9 < 10 < a ...

When I use the following code, d10a9 is MAX since 9 is sorted before 10

var lsd = new Dictionary<string, string>();
lsd.Add("a", "d10a10");
lsd.Add("b", "d10a9");
string max = lsd.Max(kvp => kvp.Value);

How can I get the Max value of the IDs with the Longest string combined?

like image 545
RRZ Europe Avatar asked Sep 14 '25 02:09

RRZ Europe


2 Answers

I think you may try to roll your own IComparer<string>

class HumanSortComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        // your human sorting logic here
    }
}

Usage:

var last = collection.OrderBy(x => x.Value, new HumanSortComparer()).LastOrDefault();
if (last != null)
    string max = last.Value;
like image 52
abatishchev Avatar answered Sep 15 '25 15:09

abatishchev


this works like a charm assuming IDs always start with "d10a":

int max = lsd.Max(kvp => Convert.ToInt32(kvp.Value.Substring(4)));
Console.Write(string.Format("d10a{0}", max));
like image 32
Ruslan Avatar answered Sep 15 '25 15:09

Ruslan