C
C#4mo 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);
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
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.
5 Replies
Angius
Angius4mo ago
You could just OrderBy() it
MODiX
MODiX4mo ago
Angius
REPL Result: Success
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.OrderBy(kv => kv.Key)
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.OrderBy(kv => kv.Key)
Result: OrderedEnumerable<KeyValuePair<float, int>, float>
[
{
"key": 0.2,
"value": 5
},
{
"key": 0.5,
"value": 4
},
{
"key": 1,
"value": 1
},
{
"key": 1.5,
"value": 2
},
{
"key": 2.5,
"value": 3
}
]
[
{
"key": 0.2,
"value": 5
},
{
"key": 0.5,
"value": 4
},
{
"key": 1,
"value": 1
},
{
"key": 1.5,
"value": 2
},
{
"key": 2.5,
"value": 3
}
]
Compile: 414.906ms | Execution: 56.561ms | React with ❌ to remove this embed.
Evyr
EvyrOP4mo ago
Thank you
cap5lut
cap5lut4mo ago
btw, a.Key < b.Key ? 1 : 0 is seems to be wrong. a negative value idicates that a is smaller, zero indicates that they are equal, and a positive value indicates that a is bigger.
Evyr
EvyrOP4mo ago
ah, thanks just tried both of those and they both work, thank you both
Want results from more Discord servers?
Add your server