Home >Backend Development >C++ >How to Sort a List Using a Custom IComparer with LINQ OrderBy?
In this article, we will explore how to leverage a custom IComparer
The scenario presented involves a generic list containing objects with an InvoiceNumber property formatted as "200906/1". The goal is to sort this list according to a custom sorting logic that considers the numerical values within the InvoiceNumber property.
Initially, a custom IComparer
The corrected MyComparer implementation is provided below:
public class MyComparer : IComparer<Object> { public int Compare(Object stringA, Object stringB) { string[] valueA = stringA.ToString().Split('/'); string[] valueB = stringB.ToString().Split('/'); if (valueA.Length != 2 || valueB.Length != 2) { return stringA.ToString().CompareTo(stringB.ToString()); } // Note: do error checking and consider i18n issues too :) if (valueA[0] == valueB[0]) { return int.Parse(valueA[1]).CompareTo(int.Parse(valueB[1])); } else { return int.Parse(valueA[0]).CompareTo(int.Parse(valueB[0])); } } }
The ApplySortCore method was modified to utilize the MyComparer:
case ListSortDirection.Ascending: MyComparer comparer = new MyComparer(); items = items.OrderByDescending( x => property.GetValue(x), comparer).ToList(); break;
Finally, to ensure that the sorted list is reflected in the bound list, the updated items collection must be assigned to the Items property:
this.Items = items;
The above is the detailed content of How to Sort a List Using a Custom IComparer with LINQ OrderBy?. For more information, please follow other related articles on the PHP Chinese website!