2013-08-14 2 views
2

클래스 형식의 목록 컬렉션이 있고 클래스에 다음 속성이 들어 있습니다. 나는 값이 상단에 와서 AM 방식으로 내 목록 모음을 정렬 할 필요가람다 식 내 목록 컬렉션을 정렬 (정렬)

- ""

class mymodel() 
{ 
public string Name{ get; set; } 
public string AMPM{ get; set; } 
} 
List<mymodel> mylist; 

AMPM 속성은 "AM"또는 "PM"또는 "MIX"또는 포함해야 그 다음에 PM 값을 입력 한 다음 "-"값을 입력하십시오.

어떻게 람다를 사용하여이 목록 콜렉션을 주문할 수 있습니까?

답변

5

다른 속성을 추가 할 수 있습니다.

class mymodel { 
    public string Name{ get; set; } 
    public string AMPM{ get; set; } 
    public int AMPM_Sort { 
     get { 
      if (AMPM == "AM") return 1; 
      if (AMPM == "PM") return 2; 
      if (AMPM == "MIX") return 3; 
      if (AMPM == "--") return 4; 
      return 9; 
     } 
    } 
} 
List<mymodel> mylist; 
var sorted = mylist.OrderBy(x => x.AMPM_Sort); 
+1

를 수행하여 정렬을 최적화합니다. 정렬은 긴 목록에 대해 더 빨리 진행됩니다. (public string AMPM {get {return _ampm;} {_ampm = value; _ampm_Sort = 적절한 값;}} – Daniel

+0

+1. 매우 간단하게 만들었지 만 실제로 그렇게 간단하지는 않다. –

0

사용자 지정 비교기를 작성하여 어떤 값이 더 높거나 낮은지를 결정할 수 있습니다. 당신이 그 매개 변수 목록을 주문하려면

는 사용자 정의 비교자를 만들어야합니다,보고를 here

0

을 가져 가라.

using System; 
using System.Collections.Generic; 

public class CustomComparer: IComparer<mymodel> 
{ 
    public int Compare(mymodel x, mymodel y) 
    { 
     if (x == null) 
     { 
      if (y == null) 
       return 0; 
      else 
       return -1; 
     } 
     // Add the comparison rules. 
     // return 0 if are equal. 
     // Return -1 if the second is greater. 
     // Return 1 if the first is greater 
    } 
} 

그리고 종류의 호출은 다음과 같습니다

List<mymodel> mylist; 
CustomComparer cc = new CustomComparer(); 
mylist.Sort(cc); 
2

이 클래스에 IComparable<T>을 구현하고 CompareTo() 재정에 precendence의 주문을 정의합니다. 이제 당신은 단순히 mylist.OrderBy(x => x)을 할 수 OrderBy(x => x);

class mymodel : IComparable<mymodel> 
{ 
    public string AMPM { get; set; } 

    public int System.IComparable<mymodel>.CompareTo(mymodel other) 
    { 
     int MyVal = AMPM == "AM" ? 1 : AMPM == "PM" ? 2 : AMPM == "MIX" ? 3 : 4; 
     int OtherVal = other.AMPM == "AM" ? 1 : other.AMPM == "PM" ? 2 : other.AMPM == "MIX" ? 3 : 4; 

     return MyVal.CompareTo(OtherVal); 
} 

}

:로 이후 람다 표현식을 사용합니다. 단순한 mylist.Sort()도 가능합니다.

-1

확장 메서드 'OrderBy'를 람다 식과 함께 사용할 수 있습니다.

var collection = new List<Mymodel> {new Mymodel {AMPM = "AM", Name = "Test1"}, 
     new Mymodel {AMPM = "PM", Name = "Test2"}, 
     new Mymodel {AMPM = "AM", Name = "Test3"}, 
     new Mymodel {AMPM = "PM", Name = "Test4"}}; 

     var sorted = collection.OrderBy(p => p.AMPM); 
+0

items. – Maarten

+0

비교 자 없이도 작동하지 않을 것입니다. –

0

당신은 클래스의 평등 &를 GetHashCode 메서드를 재정의해야합니다, 당신은 목록에서 정렬 할 수 있습니다.

2

는 마틴 솔루션을 기반으로, 내가 코드를 최적화하고 AMPM 문자열을 설정할 때 AMPM_Sort 값을 설정합니다 그 방법을

class mymodel 
    { 
     private string _ampm; 
     public string Name{ get; set; } 
     public string AMPM 
     { 
      get { return _ampm; } 
      set 
      { 
       _ampm = value; 
       AMPM_Sort = AppropriateSort(); 
      } 
     } 

     public int AMPM_Sort { get; private set; } 

     private int AppropriateSort() 
     { 
      if (AMPM == "AM") return 1; 
      if (AMPM == "PM") return 2; 
      if (AMPM == "MIX") return 3; 
      return AMPM == "--" ? 4 : 9; 
     } 
    } 
} 

List<mymodel> mylist; 
var sorted = mylist.OrderBy(x => x.AMPM_Sort); 
+0

두 버전 모두에서 성능 테스트를 수행 할 수있는 약간의 테스트 프로그램을 만들었으므로 변경 사항이이 경우에 약간의 차이가 있음을 보여줍니다. 명령 줄 : 출처 : http://pastebin.com/GESZ7CY0 결과 : http://pastebin.com/mVa7ABtD – Maarten

+0

잘 응용 프로그램에 따라 다릅니다. 큰 목록 (100 000 항목)을 여러 번 정렬해야하는 경우 당신은이 옵션을 고려할 수 있습니다. 그렇지 않으면, 당신 말이 맞습니다. 그것은 뇌 f * ck로 아무것도 아닙니다. 나는 동의합니다. – Daniel