2010-04-06 5 views
3

다음 IComparer를 작성했지만 도움이 필요합니다. 번호 목록을 정렬하려고하지만 숫자 중 일부가 채워지지 않았을 수 있습니다.이 번호를 항상 목록의 끝에 보내야합니다 .. 예를 들어 ...정수에 대한 IComparer 및 빈 문자열의 끝을 강제로

[ EMPTY] 1 [EMPTY, 3, 2

는 ... [EMPTY]

] EMPTY

1, 2, 3,해질 것이며이 될 것이다 반전 ...

3, 2, 1, [EMPTY]

아이디어가 있으십니까?

 public int Compare(ListViewItem x, ListViewItem y) 
    { 
     int comparison = int.MinValue; 
     ListViewItem.ListViewSubItem itemOne = x.SubItems[subItemIndex]; 
     ListViewItem.ListViewSubItem itemTwo = y.SubItems[subItemIndex]; 

     if (!string.IsNullOrEmpty(itemOne.Text) && !string.IsNullOrEmpty(itemTwo.Text)) 
     { 
      uint itemOneComparison = uint.Parse(itemOne.Text); 
      uint itemTwoComparison = uint.Parse(itemTwo.Text); 

      comparison = itemOneComparison.CompareTo(itemTwoComparison); 
     } 
     else 
     { 
      // ALWAYS SEND TO BOTTOM/END OF LIST. 
     } 

     // Calculate correct return value based on object comparison. 
     if (OrderOfSort == SortOrder.Descending) 
     { 
      // Descending sort is selected, return negative result of compare operation. 
      comparison = (-comparison); 
     } 
     else if (OrderOfSort == SortOrder.None) 
     { 
      // Return '0' to indicate they are equal. 
      comparison = 0; 
     } 

     return comparison; 
    } 

건배.

답변

4

귀하의 논리를 약간 벗어나 : 당신은 아마 이런 걸 원하는 그들의 중 하나가 비어있는 경우 else가 입력됩니다,하지만 당신은 단지 비어있는 목록의 끝으로 이동하려면 비어 있지 않은 것이 아닙니다. 이런 식으로 뭔가 작업을해야합니다 :

public int Compare(ListViewItem x, ListViewItem y) 
{ 
    ListViewItem.ListViewSubItem itemOne = x.SubItems[subItemIndex]; 
    ListViewItem.ListViewSubItem itemTwo = y.SubItems[subItemIndex]; 

    // if they're both empty, return 0 
    if (string.IsNullOrEmpty(itemOne.Text) && string.IsNullOrEmpty(itemTwo.Text)) 
     return 0; 

    // if itemOne is empty, it comes second 
    if (string.IsNullOrEmpty(itemOne.Text)) 
     return 1; 

    // if itemTwo is empty, it comes second 
    if (string.IsNullOrEmpty(itemTwo.Text) 
     return -1; 

    uint itemOneComparison = uint.Parse(itemOne.Text); 
    uint itemTwoComparison = uint.Parse(itemTwo.Text); 

    // Calculate correct return value based on object comparison. 
    int comparison = itemOneComparison.CompareTo(itemTwoComparison); 
    if (OrderOfSort == SortOrder.Descending) 
     comparison = (-comparison); 

    return comparison; 
} 

(I있어 수있는 "1"과 "-1"그들이 다시 전면에 비어있을 때, 내가 기억 할 수 없다 위해 :

+0

완벽하게 작동합니다. 감사! – paulio

+0

그가 빈보다 숫자가 많으면 성능이 저하되지 않습니까? – Amsakanna

+0

@Veer : 어떤 점에서? –

0

항상 empty 값으로 1을 반환하고 empty 값으로 -1을 항상 반환합니다. 이것은 비교 자 (Comparator)가 빈 값을 모든 경우에 더 큰 값으로 간주하여 정렬 된 목록의 끝에 도달해야한다는 것을 의미합니다.

물론 둘 다 비어 있다면, 동등한 0을 반환해야합니다.

0

항상 // 아래쪽/목록 끝으로 보내십시오. branch는 x 또는 y 매개 변수가 비어있을 때 실행됩니다. 즉 비어 있지 않은 값은 빈 값과 비교되는 경우이 규칙에 따라 정렬됩니다.

if (!string.IsNullOrEmpty(itemOne.Text) && !string.IsNullOrEmpty(itemTwo.Text)) 
{ 
    uint itemOneComparison = uint.Parse(itemOne.Text); 
    uint itemTwoComparison = uint.Parse(itemTwo.Text); 

    comparison = itemOneComparison.CompareTo(itemTwoComparison); 
} 
else if (!string.IsNullOrEmpty(itemOne.Text) 
{ 
    comparison = -1; 
} 
else 
{ 
    comparison = 1; 
} 
0
else 
{ 
    //ALWAYS SEND TO BOTTOM/END OF LIST. 
    if (string.IsNullOrEmpty(itemOne.Text) && string.IsNullOrEmpty(itemTwo.Text)) 
    { 
     return 0; 
    } 
    else if (string.IsNullOrEmpty(itemOne.Text)) 
    { 
     return -1; 
    } 
    else if (string.IsNullOrEmpty(itemTwo.Text)) 
    { 
     return 1; 
    } 
} 
2

실제로 다음

static void Main(string[] args) 
{ 
    List<string> ints = new List<string> { "3", "1", "", "5", "", "2" }; 
    CustomIntSort(ints, (x, y) => int.Parse(x) - int.Parse(y)); // Ascending 
    ints.ForEach(i => Console.WriteLine("[{0}]", i)); 

    CustomIntSort(ints, (x, y) => int.Parse(y) - int.Parse(x)); // Descending 
    ints.ForEach(i => Console.WriteLine("[{0}]", i)); 
} 
private static void CustomIntSort(List<string> ints, Comparison<string> Comparer) 
{ 
    int emptySlots = CountAndRemove(ints); 
    ints.Sort(Comparer); 
    for (int i = 0; i < emptySlots; i++) 
     ints.Add(""); 
} 
private static int CountAndRemove(List<string> ints) 
{ 
    int emptySlots = 0; 
    int i = 0; 

    while (i < ints.Count) 
    { 
     if (string.IsNullOrEmpty(ints[i])) 
     { 
      emptySlots++; 
      ints.RemoveAt(i); 
     } 
     else 
      i++; 
    } 
    return emptySlots; 
} 

이 질문은 최근에 내 관심을 끌었 목록의 끝에 빈을 추가 할 목록을 정렬 빈 슬롯을 제거,이에게 완전히 다른 방식으로 접근하는 것,이 비교 자 할 것입니다 그것도

class CustomComparer 
    : IComparer<string> 
{ 
    private bool isAscending; 
    public CustomComparer(bool isAscending = true) 
    { 
     this.isAscending = isAscending; 
    } 
    public int Compare(string x, string y) 
    { 
     long ix = CustomParser(x) * (isAscending ? 1 : -1); 
     long iy = CustomParser(y) * (isAscending ? 1 : -1); 
     return ix.CompareTo(iy) ; 
    } 
    private long CustomParser(string s) 
    { 
     if (string.IsNullOrEmpty(s)) 
      return isAscending ? int.MaxValue : int.MinValue; 
     else 
      return int.Parse(s); 
    } 
} 
관련 문제