I need to find the fastest way to get a small list of strings or chars in custom order. I found a lot of questions about sorting a list, but there is no question on the boar
if you are trying to write high performant poker code you really need to get rid of string/char representations and stick to int 0-12 values for deuces-aces
You say that your input is strings/chars, but its rare to find a place in high performant poker code where input is really char/string.
If you are trying to parse text boards and figuring out the hands of players performance is not so important usually.
If you are making some exhaustive board combinatorics you really need to stick to ints.
You could use a Dictionary<string, int>
where the key is the string and the value is the index.
You can even still use the List<string>
as basis:
private static readonly List<string> _List = new List<string> { "2", "3", "4", "5", "6", "7", "8", "9", "1", "J", "Q", "K", "A" };
static readonly Dictionary<string, int> Order = _List
.ToDictionary(str => str, str => _List.IndexOf(str) + 1);
Now you're able to use List.Sort which does not need to create a new list as the LINQ approaches:
var input = new List<string> { "1", "Q", "A", "8", "9" };
int i1, i2;
input.Sort((s1, s2) =>
{
Order.TryGetValue(s1, out i1);
Order.TryGetValue(s2, out i2);
return i1.CompareTo(i2);
});
Result order: 8,9,1,Q,A
A quick test revealed: StopWatch.Elapsed.TotalMilliseconds
0.0045
Dictionary.TryGetValue
returns either the index if the string was found or 0 otherwise. That's why i've used _List.IndexOf(str) + 1
above to force that found items come last.
If you want a descending order you just have to reverse it:
return i2.CompareTo(i1);