4

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.

2 Answers2

4

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
Akash KC
  • 16,057
  • 6
  • 39
  • 59
  • I really appreciate your answer and help. But this also giving an error: Can not implicitly convert type void to System.Collections.Generic.List . –  Oct 08 '17 at 00:01
  • 2
    List.sort method returns void. So, i believe, you are assigning list.sort result to variable, you should not assign that. – Akash KC Oct 08 '17 at 00:49
3

Try to order just by the property using lambda. No need to use

OrderBy(< TSource >, Func< TSource, TKey >)

In the OrderBy() you can just mention the property you want to order by (pun intended). In your class Task, you have already mentioned the property Id to be int, so you can just use that property to compare to.

Try something like this:

....
list = list.OrderBy(x => x.Id).ToList();
....