C# Sort Ignore Leading Chars Example

Sorted letters: A through Z

You want to sort an array of strings, but want some leading characters in those strings to be ignored so that the values are sorted more intuitively. For example, you want the string ".NET" to be sorted by the N, not the period.

This C# article shows how to sort while ignoring the first chars in strings. It provides example code.

Example

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. The result is that the order is unnatural and hard to scan.

Program that demonstrates sort that ignores characters [C#]

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)

Implementing sort that ignores some characters. In the second query expression, we implement the code that ignores the leading parenthesis and period characters before considering the strings. To do this, we call TrimStart on the identifier in the orderby part of the clause. This means the sort key does not include leading punctuation, which leads to a more natural sorted order.

TrimStart Method OrderBy Clause

Optimized?

Question and answer

No, the code here is not optimally fast. However, 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 Examples

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. This can lead to more natural, usable sorted arrays.

Sort Examples
.NET