I have a simple sorting issue using mono... If I run the following code on Mac and Windows I get a different result:
using System;
using System.Linq;
public class Program
{
public static void Main()
{
var testArray = new string[]
{
"PȺFftFyaheâµ", "P6ZijTµȺut"
}.OrderBy(t => t);
foreach (var item in testArray)
{
Console.WriteLine(item);
}
}
}
Result windows
P6ZijTµȺut
PȺFftFyaheâµ
Result Mac
PȺFftFyaheâµ
P6ZijTµȺut
Does anyone has a clue how this is possible and what we can do to fix it?
Thanks the fix was a string comparer
class Program
{
static void Main(string[] args)
{
var testArray = new string[] { "PȺFftFyaheâµ", "P6ZijTµȺut" }.OrderBy(t => t, StringComparer.Ordinal);
foreach (var item in testArray)
{
Console.WriteLine(item);
}
}
}
This is to be expected, given differences in culture. From the string.CompareTo(string)
documentation:
This method performs a word (case-sensitive and culture-sensitive) comparison using the current culture. For more information about word, string, and ordinal sorts, see
System.Globalization.CompareOptions
.
To make sure the code behaves the same way on multiple systems, you can either ensure you use the same culture on all systems, or specify a culture-insensitive comparison (e.g. StringComparer.Ordinal
) as a second argument to OrderBy
.
See more on this question at Stackoverflow