Lets say i have the strings abc_
and abc2_
. Now, normally when sorting i C# abc2_
would come after abc_
, leaving the result:
abc_
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With