Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 泛型列表和IComparable排序错误:无法转换lambda表达式_C#_.net_Sorting_Lambda_Icomparable - Fatal编程技术网

C# 泛型列表和IComparable排序错误:无法转换lambda表达式

C# 泛型列表和IComparable排序错误:无法转换lambda表达式,c#,.net,sorting,lambda,icomparable,C#,.net,Sorting,Lambda,Icomparable,我已经实现了自己的GenericList和Task类,例如: 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 Err

我已经实现了自己的GenericList和Task类,例如:

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;}
}
公共泛型列表,其中T:Task
{
公共列表=新列表();
....
公共无效排序()
{
list=list.Sort((a,b)=>b.Id.CompareTo(a.Id)>0);
//这里我得到了VisualStudioIDE的错误警告
//错误:无法将lambda表达式转换为
//“System.Collections.Generic.IComparer”,因为它不是委托类型
}
}
公开课任务
{
公共int Id{get;set;}
公共任务(int-ID)
{Id=Id;}
}
这里我得到了VisualStudioIDE错误警告:Can 不将lambda表达式转换为 “System.Collections.Generic.IComparer”,因为它不是委托 类型

我甚至尝试在Sort()方法中使用Compare.Create方法实现以下内容:

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
list=list.OrderBy(x=>x.Id,
比较器创建((x,y)=>x.Id>y.Id-1:x.Id
但我仍然得到了错误

在我的sort in GenericList实现中,我试图根据任务ID对任务进行排序。有人能帮我吗?我怎样才能做到这一点


感谢您的帮助。提前感谢。

首先,不要将
Sort()
结果分配给变量,因为它是
就地排序的。
并将代码更改为

list.Sort((a, b) => b.Id.CompareTo(a.Id)); // sort and keep sorted list in list itself

尝试使用lambda按属性排序。不需要使用

OrderBy(,Func

在OrderBy()中,您只需提及要按其排序的属性(双关语)。在类任务中,您已经提到属性Id为int,因此您可以使用该属性进行比较

试着这样做:

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

我真的很感谢你的回答和帮助。但这也给出了一个错误:不能隐式地将类型void转换为System.Collections.Generic.List.List.sort方法返回void。所以,我认为,您正在将list.sort结果赋值给变量,不应该将其赋值。