Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change C# sorting behaviour

Tags:

c#

sorting

linq

Lets say i have the strings abc_ and abc2_. Now, normally when sorting i C# abc2_ would come after abc_, leaving the result:

  1. abc_
  2. abc2_

I am using this to sort, if it matters:

     var element = from c in elements
     orderby c.elementName ascending
     select c;

How can i change this? I want abc_ to come last. Reversing is not an option because the list is contains more than two elements.

like image 936
Erik Avatar asked Jan 21 '23 23:01

Erik


2 Answers

The simplest solution is to use the ordinal string comparer built in to the .NET Framework:

var element = from c in elements
    .OrderBy(c => c.elementName, StringComparer.Ordinal) 
    select c; 

No custom Comparer class needed!

like image 106
luksan Avatar answered Jan 25 '23 11:01

luksan


The OrderBy method can potentially take an IComparer<T> argument. (I'm not sure if that overload can be used with query comprehension syntax, or if it's only available when using the fluent extension method syntax.)

Since it's not clear exactly what your sort algorithm should involve, I'll leave implementing the required IComparer<T> as an exercise for the reader.

like image 30
LukeH Avatar answered Jan 25 '23 11:01

LukeH