1

我有许多对象,都来自同一个类(ColorNum)每个对象都有 2 个成员变量(m_Color 和 m_Number)

例子:

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

这 4 个对象在 ColorNumList 中

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

现在我想对列表进行排序,以便 mColor = "Red" 的对象位于顶部。我不关心剩余对象的顺序。

我的谓词方法应该是什么样的?

4

3 回答 3

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) );
于 2009-07-08T11:47:58.960 回答
0
ColorNumList.Sort((x, y) => x.m_Color == Red ? 1 : (y.m_Color == Red ? -1 : 0));
于 2009-07-08T11:52:58.060 回答
0

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

[C#] public static void Sort(Array, Array, int, int, IComparer);

您需要实现一个比较两个对象并返回一个值的函数,该值指示一个对象是否小于、等于或大于另一个对象。

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

You need to write a class that implemenets the IComparer interface.

I haven't been using C#, but here is the VB equivalent:

Class ColorCompare Implements 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
于 2009-07-08T11:58:33.633 回答