Home
C#
Sort and Ignore Chars
This page was last reviewed on Apr 26, 2022.
Dot Net Perls
Sort, ignore lead chars. In C# programs strings sometimes contain characters that do not matter. These characters can be ignored while sorting.
Sorting details. For example, consider that we can ignore the period on the start of ".NET". The string will be sorted by the N not the period.
Sort
This program uses a string array with some values that have leading punctuation. The value "(Z)" is by default sorted by its parenthesis character. The value ".NET" is sorted by the period.
Array
And The result is that the order is unnatural and hard to scan. The period should be ignored.
Info In the second query, we implement the code that ignores the leading parenthesis and period characters before considering the strings.
Detail We call TrimStart on the identifier in the orderby part of the clause. The sort key does not include leading punctuation.
String TrimEnd, TrimStart
orderby
using System; using System.Linq; class Program { static void Main() { string[] elements = { "A", "(Z)", ".NET", "NO" }; { var sorted = from element in elements orderby element select element; foreach (var element in sorted) { Console.WriteLine(element); } } Console.WriteLine("---"); { var sorted = from element in elements orderby element.TrimStart('(', '.') select element; foreach (var element in sorted) { Console.WriteLine(element); } } } }
(Z) .NET A NO --- A .NET NO (Z)
Discussion. The code here is not optimally fast. If you want to optimize the performance of this method, consider implementing IComparer and using Array.Sort and sorting the array in-place.
Array.Sort
Benchmark
IComparable
Summary. We can implement custom sorts using query expressions. We can sort on mutated strings—such as ones that are stripped of leading characters. This can lead to more naturally sorted arrays.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 26, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.