Sunday, May 1, 2016

C#: Specific Culture Sorting without using CurrentThread.CurrentCulture

You can use StringComparer Class which provide you custom sorting/comparing method without having mess with Thread.CurrentThread.CurrentCulture at all.
According to Microsoft Docs, you can sort your data with specific culture by setting Thread.CurrentThread.CurrentCulture. However, this way is not allowed when you are not actually own that thread. For example, when you use Threadpool or you are writing addins like ArcObjects, etc.

So, I spent my time researching and found that I can use StringComparer Class. This class provide you custom sorting/comparing method without having mess with Thread.CurrentThread.CurrentCulture at all.

For example, Code below will sort string in Thai language (ภาษาไทย).
//your data.
List<string> myList = new List<string>() { "ไม่", "มันเทศ", "กันเอง", "กบ", "ขวด", "ไทย", "จักร", "ใจ", "Test", "asdf", "AAAA" };

//create culture info and comparer
CultureInfo thaiCulture = new CultureInfo("th-TH", false);
StringComparer thaiStringComparer = StringComparer.Create(thaiCulture, true);

//sort it!
myList.Sort(thaiStringComparer);


Moreover, you can do custom string comparison by using StringComparer.Compare and StringComparer.Equals method.



Happy Coding!

No comments:

Post a Comment