natural sort in csharp

You can achieve natural sorting in C# by using the HumanSortComparer class from the Microsoft.CSharp namespace. This comparer performs a natural sort on strings that contain both numbers and strings.

Here is an example of how you can perform natural sort in C# using HumanSortComparer:

main.cs
using System;
using Microsoft.CSharp;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<string> items = new List<string> { "item10", "item5", "item1", "item20", "item2" };

        items.Sort(new HumanSortComparer());

        foreach (var item in items)
        {
            Console.WriteLine(item);
        }
    }
}
363 chars
19 lines

In this code snippet, we create a list of strings that contain alphanumeric values. We then sort the list using HumanSortComparer and iterate over the sorted list to display the items in natural sort order.

related categories

gistlibby LogSnag