How to

create comparer for collection sorting

Published: 8. January 2009 | Updated: 8. January 2009
License: Microsoft Public License (MS-PL)
Categories: Collections, Implementations
Tags: C# Collections Design Patterns
Was this snippet helpful for you? YESYES / NONO

Import namespace

using System.Collections.Generic;

Comparer Implementation

public class StringLengthComparer : Comparer<string>
{
    public override int Compare(string param1, string param2)
    {
        if (param1.Length < param2.Length)
        {
            return -1;
        }
        else if (param1.Length > param2.Length)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
}

Use

List<string> collection = new List<string>();
collection.Add("abcdef");
collection.Add("abcde");
collection.Add("abc");
collection.Add("a");
collection.Add("abcdefgh");
collection.Add("abcde");

collection.Sort(new StringLengthComparer());

foreach (string item in collection)
{
    Console.WriteLine(item);
}
Console Output:
a
abc
abcde
abcde
abcdef
abcdefgh
Send us feedback about this snippet »



Related Snippets: