How can I custom sort a keyvaluepare list in C#?

JunYoungLee 161 Reputation points
2022-06-20T15:33:55.4+00:00

I want to apply custom sort to myList after converting New_RNR_PathDic of Dictionary<string, string> type to List<KeyValuePair<string, string>> myList.
Below is my code, myList.Sort(new Sort_CSVDate()); The code could not be executed because an error occurred at this line. Is there something wrong with my code?

List<KeyValuePair<string, string>> myList = New_RNR_PathDic.ToList();  
myList.Sort(new Sort_CSVDate());        //Error : cannot conver to 'System.Collections.Generic.IComparer  
  
  
public class Sort_CSVDate : IComparer<object>  
    {  
        public int Compare(object x, object y)  
        {  
            //KeyValuePair<string, string>  
            var x1 = (KeyValuePair<string, string>)x;  
            var y1 = (KeyValuePair<string, string>)y;  
  
            var x2 = x1.Value;  
            var y2 = y1.Value;  
  
            var cast_x = x1.ToString().Substring(x1.ToString().IndexOf("-") + 1, x1.ToString().Length - x1.ToString().IndexOf("-") - 1).Replace(".csv", "");   
            var cast_y = y1.ToString().Substring(y1.ToString().IndexOf("-") + 1, y1.ToString().Length - y1.ToString().IndexOf("-") - 1).Replace(".csv", "");  
  
            DateTime date_x = DateTime.ParseExact(cast_x, "dd-MMM-yyyy HH.mm.ss", CultureInfo.InvariantCulture);  
            DateTime date_y = DateTime.ParseExact(cast_y, "dd-MMM-yyyy HH.mm.ss", CultureInfo.InvariantCulture);  
  
            return date_x.CompareTo(date_y);  
        }  
    }  
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,677 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,281 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
766 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 112.5K Reputation points
    2022-06-20T15:41:23.917+00:00

    To fix the compilation error, try this definition: public class Sort_CSVDate : IComparer<KeyValuePair<string, string>>.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful