Sorting a Custom Class List<T> in C#: Practical Approaches Using Delegates and IComparable Interface

Dec 05, 2025 · Programming · 11 views · 7.8

Keywords: C# | Sorting | Custom Class | Delegate | IComparable

Abstract: This article explores multiple methods for sorting a List<cTag> by the date property in C#, focusing on the delegate-based approach from the best answer. It provides detailed explanations and code examples, while also covering alternative solutions such as implementing the IComparable interface and using LINQ. The analysis addresses issues with string-based date sorting and offers optimization tips by converting dates to DateTime type, aiming to help developers understand core sorting mechanisms in C# collections.

Introduction

Sorting collections is a common task in C# programming, especially when dealing with custom classes. Based on the provided Q&A data, this article discusses how to sort a List<cTag> by the date property, where the date is in dd.MM.yyyy format. We start with the delegate method from the best answer and expand to other technical solutions.

Delegate Sorting Method

According to the best answer, using a delegate is a concise and effective way to sort. This approach defines comparison logic through an anonymous function, directly calling the List.Sort method. Example code is as follows:

List<cTag> week = new List<cTag>();
// Assume elements are added to the list
week.Sort(delegate(cTag c1, cTag c2) { return c1.date.CompareTo(c2.date); });

Here, the delegate takes two cTag parameters c1 and c2 and returns the result of c1.date.CompareTo(c2.date). CompareTo is the default comparison method for strings, based on lexicographic order. However, since the date is stored as a string, this may lead to inaccurate sorting, e.g., comparing "01.01.2023" and "10.01.2022" might not reflect chronological order.

Implementing the IComparable Interface

Another method is to implement the IComparable<cTag> interface in the cTag class, as described in Answer 2. This requires defining a CompareTo method:

public class cTag : IComparable<cTag>
{
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other)
    {
        return date.CompareTo(other.date);
    }
}

After implementation, you can directly call week.Sort(). But similarly, string comparison may not be suitable for date sorting. To improve this, it is recommended to change the date property type to DateTime and use DateTime.Parse for conversion:

public class cTag : IComparable<cTag>
{
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other)
    {
        return date.CompareTo(other.date);
    }
}
// Convert date when creating an instance
cTag tag = new cTag { date = DateTime.Parse("01.01.2023") };

This way, DateTime.CompareTo ensures correct chronological sorting.

LINQ Sorting Method

Answer 3 proposes using the LINQ OrderBy method for sorting:

week = week.OrderBy(w => DateTime.Parse(w.date)).ToList();

This method specifies the sort key via a Lambda expression and returns a new sorted list. It combines the flexibility of delegates with the advantage of type conversion, but note that DateTime.Parse may throw exceptions if the date format is invalid.

Conclusion and Recommendations

When sorting custom class lists in C#, the delegate method offers quick implementation for simple scenarios; the IComparable interface enhances class reusability; and LINQ provides a declarative programming style. For date sorting, it is recommended to store dates as DateTime type to avoid issues with string comparison. Developers should choose the appropriate method based on specific needs, considering error handling and performance optimization.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.