Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort case insensitive with System.Dynamic.Linq?

Tags:

c#

linq

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.

like image 247
Adrian Rosca Avatar asked Mar 31 '15 22:03

Adrian Rosca


2 Answers

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);
}
like image 109
Moss Avatar answered Sep 22 '22 12:09

Moss


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

like image 26
user1951575 Avatar answered Sep 23 '22 12:09

user1951575