Search code examples
c#.netlistgeneric-collections

Sort List alternative in c#


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) );