tags:

views:

78

answers:

3

private List nodes = new List();

there is a label field inside ISilverNodeModel class of type string.

suppose the nodes list is:

Malcolm, Sym, Eric, Sandrea

I want malcolm and Sandrea always on top and rest to be sorted.

I am doing this but it sorts all :

nodes.Sort((node1, node2) => node1.Label. CompareTo( node2.Label));

+5  A: 

You can write your own IComparer, and use that implementation in the Sort method.

Your implementation could then determine that malcolm and sandra are always smaller then any other label.

public class MySorter : IComparer<ISilverNodeModelClass>
{
   public int Compare( ISilverNodeModelClass left, ISilverNodeModelClass right )
   {
       if( left.Label.Equals (right.Label) )
           return 0;

       if( left.Label == "malcolm" || left.Label == "sandra" )
          return Int32.MinValue;

       if( right.Label == "malcolm" || right.Label == "sandra" )
           return Int32.MaxValue;

       return Comparer<string>.Default.Compare (left.Label, right.Label);
   }
}
Frederik Gheysels
Ok the problem solved : Following u r code. Thanks
Malcolm
+1  A: 

If you're on .NET 3.5, there's a nice way to do it using LINQ:

    List<string> topLabels = new List<string> { "Malcolm", "Sandrea" };
    nodes = nodes
        .OrderByDescending(node => topLabels.Contains(node.Label))
        .ThenBy(node => node.Label)
        .ToList();
Mark Byers
A: 
                    nodes.Sort((node1, node2) =>
                        {
                            if (node1.Label.Equals(node2.Label))
                            {
                                return 0;
                            }
                            if (node1.Label == "Favorites" || node1.Label == "Recent")
                                {
                                    return Int32.MinValue;
                                }
                            if (node2.Label == "Favorites" || node2.Label == "Recent")
                            {
                                return Int32.MaxValue;
                            }
                            return node1.Label.CompareTo(node2.Label);
                         });  
Malcolm