Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List and IComparable Sorting Error: Can not convert lambda expression

I have implemented my own GenericList and Task classes such as:

public GenericList<T> where T: Task
{
  public List<T> list = new List<T>();
  ....
  public void Sort()
  {
   list = list.Sort((a,b) => b.Id.CompareTo(a.Id) > 0);
   //here I am getting the Error Warning by Visual Studio IDE
   //Error: Can not convert lambda expression to
   //'System.Collections.Generic.IComparer<T>' because it is not a delegate type
  }
}

public class Task
{
  public int Id {get; set;}
  public Task(int ID)
  {Id = ID;}
}

here I am getting the Error Warning by Visual Studio IDE Error: Can not convert lambda expression to 'System.Collections.Generic.IComparer' because it is not a delegate type

I even tried to implement the following instead in the Sort() method using Compare.Create method:

list = list.OrderBy(x => x.Id,
            Comparer<Task>.Create((x, y) => x.Id > y.Id ? 1 : x.Id < y.Id ? -1 : 0));
//Here the Error: the type argument for the method can not be inferred

But I am still getting the error.

I am trying to sort the tasks based on their Ids in my implementation of Sort in GenericList. Can someone help me how may I be able to achieve this?

Any help is appreciated. Thank you in advance.


1 Answers

First of all, don't assign Sort() result to variable as it's in-place sorting. And change your code to

list.Sort((a, b) => b.Id.CompareTo(a.Id)); // sort and keep sorted list in list itself
like image 51
Akash KC Avatar answered Nov 03 '25 22:11

Akash KC