Home > Backend Development > C++ > How to Correctly Sort a List Using a Custom IComparer with Linq OrderBy?

How to Correctly Sort a List Using a Custom IComparer with Linq OrderBy?

Linda Hamilton
Release: 2025-01-01 04:11:10
Original
327 people have browsed it

How to Correctly Sort a List Using a Custom IComparer with Linq OrderBy?

Using Custom IComparer with Linq OrderBy

Problem

You have a generic List where MyClass contains an InvoiceNumber property with values like 200906/1. You want to use a custom IComparer to sort the list in a specific order. However, when using your custom comparer, the list is still sorted incorrectly.

Answer

There are two issues in your code:

  1. The custom comparer you provided does not correctly sort the numbers. You should convert the InvoiceNumber values to numbers and sort based on those numbers.
  2. You are not updating the BindingList with the sorted items. After sorting the list, you need to assign the sorted list to the Items property of the BindingList.

Here is the corrected custom comparer:

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 String.Compare(stringA.ToString(), 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]));
        }
    }

}
Copy after login

And here is the corrected code to update the BindingList:

case ListSortDirection.Ascending:
    MyComparer comparer = new MyComparer();
    items = items.OrderByDescending(x => property.GetValue(x), comparer).ToList();
    break;
default:
    // Handle descending sort direction here
    break;
}

this.Items = items;
Copy after login

The above is the detailed content of How to Correctly Sort a List Using a Custom IComparer with Linq OrderBy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template