C#C
C#17mo ago
Evyr

✅ Struggling to use custom comparer with a list of KeyValuePairs

I'm trying to sort a list of keyvaluepairs on the key. I've defined an IComparer using Comparer.Create, but the list after sorting is identical to before. I can't use a SortedList because that requires unique keys.

IComparer<KeyValuePair<float, int>> comp = Comparer<KeyValuePair<float, int>>.Create((a, b) => a.Key < b.Key ? 1 : 0);
List<KeyValuePair<float, int>> li = [
    new(1f, 1),
    new(1.5f, 2),
    new(2.5f, 3),
    new(0.5f, 4),
    new(0.2f, 5)
    ];
li.Sort(comp);

foreach (var kvp in li)
    Console.WriteLine(kvp.Key + ", " + kvp.Value);


The output looks like
1, 1
1.5, 2
2.5, 3
0.5, 4
0.2, 5

Whereas I'd expect it to be sorted in either ascending or descending order.
Was this page helpful?