I need a function that converts an array of strings into a string that is sortable in the same order as if you would sort the inputs (sort first input argument, if equal sort second etc…)
In native code, separating the strings with \0 would do, but somehow
(“a” + char.MinValue + “2”).CompareTo(“a1”) equals to 1!
What is going on and is it possible to create such a function?
public static string StringsToKey(params string[] values)
EDIT: This is the test I want to succeed:
Assert.IsTrue(MiscUtils.StringsToKey("a", "2").CompareTo(MiscUtils.StringsToKey("a1")) < 0);
I would like to avoid using CompareOrdinal because I’m not always in control of how the key would be sorted. Also, ordinal might yield incorrect sorting order on international sets…
Unlike null-terminated C-style strings, a .NET string may contain null characters, so in the general case, there is no separator that will guarantee to sort lower than any valid character in a string.
Of course if you’re sure your strings don’t contain nulls and ordinal sorting is OK, some of the solutions already posted will work.
But I’d say don’t even attempt it. Writing a comparer for your string arrays will be more efficient (avoiding creating the temporary strings) and better expresses your intent. There are lots of ways this could be done, including the following (compares IList<string> rather than string[] for more flexibility, and supports culture-sensitive comparisons):
The above code is untested and possibly buggy, but I’m sure you get the idea.