Home > Back-end >  C# Sorting string list with underscore and hyphen
C# Sorting string list with underscore and hyphen

Time:12-10

I have a List<string> with values SK-Disbur and SK_Recon. When I sort the list, what should be the output?

I am getting:

SK_Recon
SK-Disbur

I was expecting the other way around with Disbur before Recon, since hyphen comes before underscore.

Here is my code:

List<string> list=new List<string>();
list.Add("SK-Disbur");
list.Add("SK_Recon");
list.Sort();
for(int i=0;i <list.Count;i   )
{
    Console.WriteLine(list[i]);
}

CodePudding user response:

.NET doesn't use ASCII, it uses Unicode UTF-16. When you perform a string sort, By default .NET are using the current culture's rules for sorting. In this case, those rules indicate that "_" comes before "-". You can get the result you expect by using the "ordinal" string comparer:

    List<string> list = new List<string>()
    {
    "SK-Disbur",
    "SK_Recon",
    "SK1",
    "SK2"
    };

    list.Sort(StringComparer.Ordinal);

    for (int i = 0; i < list.Count; i  )
    {
        Console.WriteLine(list[i]);
    }

you will get this result

SK-Disbur
SK1
SK2
SK_Recon

but if you use list.Sort() (by default) the result is very different

SK_Recon
SK-Disbur
SK1
SK2

CodePudding user response:

By default list.Sort() uses the current culture's rules for sorting. That means each character is sorted using a linguistic sort (alphabetic sequence). You should use ordinal sorting so that its sorted by the binary value of each character. Try: list.Sort(StringComparer.Ordinal);

  •  Tags:  
  • c#
  • Related