C# Sort, Ignore Leading Chars

This C# example sorts a string array while ignoring the leading chars in the strings.
Sort, ignore lead chars. Strings sometimes contain characters that do not matter. These characters can be ignored while sorting. For example we can ignore the period on the start of ".NET". The string will be sorted by the N not the period.
To begin, this program uses a four-element string array with some values that have leading punctuation. The value "(Z)" is by default sorted by its parenthesis character, not the Z. 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.

TrimStart: We call TrimStart on the identifier in the orderby part of the clause. The sort key does not include leading punctuation.

TrimEnd, TrimStartorderby
C# program that sorts, ignores characters 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); } } } } Output (Z) .NET A NO --- A .NET NO (Z)
Discussion. The code here is not optimally fast. But it is pretty clear and easy to understand. If you want to optimize the performance of this method, I would consider implementing IComparer and using Array.Sort and sorting the array in-place.Array.Sort
Summary. You can implement custom sorts using the query expression syntax in the C# language. This gives you the ability to sort on slightly mutated strings, such as ones that are stripped of their leading characters.

And: This can lead to more natural, usable sorted arrays, and better interface usability.

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls