2009-07-08 53 views
1

我有多個對象,全部來自同一類(ColorNum)每個對象有2個構件variabels(m_Color和m_Number)排序列表替代在c#

實施例:

ColorNum1(Red,25) 
ColorNum2(Blue,5) 
ColorNum3(Red,11) 
ColorNum4(White,25) 

的4個對象是在ColorNumList

List<ColorNum> ColorNumList = new List<ColorNum>(); 

現在我要訂購列表中,以便與mColor =「紅」的對象是在頂部。 我不在乎剩下的物體的順序。

我的謂詞方法應該是什麼樣子?

回答

11

使用LINQ:

var sortedRedAtTop = 
    from col in ColorNumList 
    order by col.Color == Red ? 1 : 2 
    select col; 

或者列表的排序方法:

ColorNumList.Sort((x,y) => 
    (x.Color == Red ? 1 : 2)-(y.Color == Red ? 1 : 2)); 
+0

你的LINQ的解決方案是整齊的。 – tomfanning 2009-07-08 12:03:08

0
ColorNumList.Sort((x, y) => x.m_Color == Red ? 1 : (y.m_Color == Red ? -1 : 0)); 
0

http://msdn.microsoft.com/en-us/library/system.array.sort(VS.71).aspx

[C#]公共靜態無效的排序(數組,數組,INT, int,IComparer);

您需要實現一個函數,該函數比較兩個對象並返回一個值,指示一個是小於,等於還是大於另一個。

http://msdn.microsoft.com/en-us/library/system.collections.icomparer.compare(VS.71).aspx

你需要編寫implemenets IComparer接口的類。

我沒有使用C#,但這裏是VB相當於:

類ColorCompare 器具的IComparer

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare 
     Dim xc As ColorNum = TryCast(x, ColorNum) 
     Dim yc As ColorNum = TryCast(y, ColorNum) 
     If x.color = Red Then 
      Return 1 
     ElseIf y.color = Red Then 
      Return -1 
     Else 
      Return 0 
     End If 
    End Function 
End Class