开发者

Sort the generic list and allow two names always to be on top and rest sorted

private List nodes = new List();

there is a label fie开发者_开发知识库ld 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));


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜