Search code examples
c#.net-coreicu

Sort list of strings using icu-dotnet library for Myanmar collation


I want to sort list of strings using icu-dotnet library for Myanmar collation.

It throw an exception while creating collator for myanmar.

var cultureInfo = new CultureInfo("my-MM");
using (var collator = Collator.Create(cultureInfo.Name))
{
    int compareResult = collator.Compare("သန်တ", "သန္တ");
}

Solution

  • This throws an ArgumentException because there are no predefined collation rules for my-MM in ICU. However, there are rules for my, so the following would work:

    var cultureInfo = new CultureInfo("my");
    

    Or you could allow the fallback to my by passing FallBackAllowed:

    using (var collator = Collator.Create(cultureInfo.Name, Collator.Fallback.FallbackAllowed))
    {
    }
    

    You can see the predefined collators by looking at the icu4c source tree.

    The full code to sort a list of strings:

    var list = new List<string> {"foo", "baz", "bar", "zoo"};
    
    using (var collator = Collator.Create("en-US"))
    {
        list.Sort((s1, s2) => collator.Compare(s1, s2));
    }