我已经实现了自己的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;}
}
这里我收到了Visual错误警告:无法将lambda表达式转换为“System.Collections.Generic.IComparer”,因为它不是委托类型
我甚至尝试使用Compare.Create方法在Sort()方法中实现以下内容:
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
但我还是会犯错误。
在GenericList中实现排序时,我试图根据它们的Ids对任务进行排序。有人能帮我吗?我怎样才能做到这一点?
任何帮助都是非常感谢的。提前谢谢你。
发布于 2017-10-08 13:22:00
尝试使用lambda按属性订购。不需要使用
OrderBy(< TSource >,Func< TSource, TKey >)
在OrderBy()中,您只需提及您希望通过(双关意)订购的属性。在类任务中,您已经提到了要为int的属性Id,因此您可以只使用该属性进行比较。
试着做这样的事情:
....
list = list.OrderBy(x => x.Id).ToList();
....
发布于 2017-10-07 23:31:42
首先,不要将Sort()
结果赋值给变量,因为它是in-place sorting
。并将代码更改为
list.Sort((a, b) => b.Id.CompareTo(a.Id)); // sort and keep sorted list in list itself
https://stackoverflow.com/questions/46625992
复制相似问题