Reputation: 7392
I use System.Linq.Dynamic to order an items list.
items = items.AsQueryable().OrderBy("Name ASC");
To my surprise, lowercase names gets ordered after the capital cased names, so the items are returned something like this.
Ape
Cat
Dog
alligator
ant
beetle
I expected this order:
alligator
ant
Ape
beetle
Cat
Dog
Is there a way to get the correct order? Checked all method signatures for OrderBy and googled around, but nada.
Upvotes: 8
Views: 8493
Reputation: 29
I have faced the same issue and found no easy solution over the internet. Then I was trying in many ways and finally got a very simple way. It completely worked for me. My solution is
string sort = "Name ASC";
string[] data = sort.Split(" ");
items.OrderBy($"{data[0].ToUpper() data[1]}");
Now the output is alligator, ant, Ape, beetle, Cat, Dog
Upvotes: 0
Reputation: 895
You do not need to create a custom comparer because there's already a StringComparer
class which derives from IComparer
.
words.OrderBy (x => x, StringComparer.OrdinalIgnoreCase)
This way, you do not need to create different IComparer
implementations if you wanted to use other string comparison methods, like StringComparer.InvariantCultureIgnoreCase
.
However, this might be desirable depending on your situation. For example, I do have multiple extension methods defined in LINQPad, like OrderBySelfInvariantCultureIgnoreCase
, because it is convenient to use this with code completion rather than typing out the equivalent code by hand:
public static IEnumerable<string> OrderBySelfInvariantCultureIgnoreCase(this IEnumerable<string> source)
{
return source.OrderBy (x => x, StringComparer.InvariantCultureIgnoreCase);
}
Upvotes: 11
Reputation: 725
You must create a custom comparer, such as:
public void Main()
{
String[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
var sortedWords = words.OrderBy(a => a, new CaseInsensitiveComparer());
ObjectDumper.Write(sortedWords);
}
public class CaseInsensitiveComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y, StringComparison.OrdinalIgnoreCase);
}
}
Found @ https://code.msdn.microsoft.com/SQL-Ordering-Operators-050af19e
Upvotes: 2