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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 26, 2022 (edit link).