Sort List alternative in c#
-
11-09-2019 - |
Question
I have a number of objects, all from the same class(ColorNum) Each object has 2 member variabels (m_Color and m_Number)
Example:
ColorNum1(Red,25)
ColorNum2(Blue,5)
ColorNum3(Red,11)
ColorNum4(White,25)
The 4 objects are in the ColorNumList
List<ColorNum> ColorNumList = new List<ColorNum>();
Now I want to order the list so the objects with mColor = "Red" is in the top. I dont care about the order of the remaining objects.
What should my predicate method look like?
Solution
Using linq:
var sortedRedAtTop =
from col in ColorNumList
order by col.Color == Red ? 1 : 2
select col;
Or the list's sort method:
ColorNumList.Sort( (x,y) =>
(x.Color == Red ? 1 : 2)-(y.Color == Red ? 1 : 2) );
OTHER TIPS
ColorNumList.Sort((x, y) => x.m_Color == Red ? 1 : (y.m_Color == Red ? -1 : 0));
See http://msdn.microsoft.com/en-us/library/system.array.sort(VS.71).aspx
[C#] public static void Sort(Array, Array, int, int, IComparer);
You need to implement a function that compares two objects and returns a value indicating whether one is less than, equal to or greater than the other.
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