2017-10-07 12 views
0

를 변환 할 수 없습니다 : (일반 목록과에서 IComparable 정렬 오류 : 나는 같은 내 자신의 GenericList 및 작업 클래스를 구현 한 람다 식을

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

나는 심지어 정렬 대신 다음 구현하기 위해 노력했다) 방법을 사용하여 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 

하지만 여전히 오류가 발생합니다.

Sort를 GenericList 내에서 구현할 때 Id를 기반으로 작업을 정렬하려고합니다. 누군가가 어떻게이 일을 성취 할 수 있을까요?

도움을 주시면 감사하겠습니다. 미리 감사드립니다.

답변

0

으로 변경하십시오. 람다를 사용하여 재산으로 주문하십시오. 필요가 방금 (의도 된 말장난)에 의한 주문하려는 속성을 언급 할 수 있습니다)에있는 OrderBy (에서

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

를 사용하지합니다. 클래스 Task에서 이미 속성 ID를 int로 언급 했으므로 비교할 속성을 사용할 수 있습니다. 이 같은

시도 뭔가 :

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

도움 주셔서 감사합니다. 그것은 완벽하게 작동했습니다. –

2

먼저 Sort() 결과를 변수에 할당하지 마십시오 (in-place sorting). 코드를

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

은 정말 당신의 대답과 도움을 주셔서 감사합니다. 그러나 이것도 오류가 발생합니다 : void 형식을 System.Collections.Generic.List 으로 암시 적으로 변환 할 수 없습니다. –

+1

List.sort 메서드는 void를 반환합니다. 그래서, 당신은 변수에 list.sort 결과를 할당한다고 믿습니다. 할당해서는 안됩니다. –