在keyvaluepairs的绑定列表中自定义排序

时间:2014-04-06 20:11:01

标签: c# winforms sorting bindinglist

我有一个keyvaluepair的绑定列表,填充了dynamicaly。

  BindingList<KeyValuePair<int, string>> Homelist = new BindingList<KeyValuePair<int, string>>();
  foreach (ListItem item in listBox2.Items)
    {
     Homelist.Add(new KeyValuePair<int, string>(item.Id, item.Name));
    }

列表中包含键(id)和值(文本),如图所示

enter image description here

我想对前5个项目asc进行排序,然后其余项目也是asc。排序必须是按值而不是按键。 例如:如果我有值:4,5,8,7,6,10,9,3,2,1,22,排序结果必须是4,5,6,7,8,1,2,3, 9,10,22。任何想法?

解决了答案:

     public int Compare(KeyValuePair<int,string> a, KeyValuePair<int,string> b)
    {
        return a.Value.CompareTo(b.Value);
    }
 List<keyvaluepair><int,>> Playinglist = new List<keyvaluepair><int,>>();
            for (int i = 0; i < 5; i ++)
            {
                Playinglist.Add(Homelist[i]);
            }
            Playinglist.Sort(Compare);

            List<keyvaluepair><int,>> Benchlist = new List<keyvaluepair><int,>>();
            for (int i = 5; i < Homelist.Count(); i++)
            {
                Benchlist.Add(Homelist[i]);
            }
            Benchlist.Sort(Compare);

            //union 2 lists
            var unionedList = new List<keyvaluepair><int,>>();
            unionedList.AddRange(Playinglist.Union(Benchlist));

            Homelist.Clear();
            for (int i = 0; i < unionedList.Count(); i++)
            {
                Homelist.Insert(i, unionedList[i]);
            }
            game.GetHomelist = Homelist;

1 个答案:

答案 0 :(得分:0)

Tony Hopkinson所说的想法是将名单分成两部分。分别对它们进行排序,然后将它们连接起来。之后清除绑定列表并从连接列表中填充。排序只能在List&lt;&gt;中应用。而不是BindLists&lt;&gt;。答案是编辑问题