如何在不更改索引的情况下对列表框进行排序

时间:2013-12-13 13:13:53

标签: c# visual-studio sorting listbox

我有一个列表框,我从列表中填写。字符串是另一个列表中对象的属性。当从列表中选择某些内容时,我使用索引来选择相关对象(当然,它与List中的名称具有相同的索引)。但是当我按列表(按名称)对列表进行排序时,每个字符串的索引都会发生变化,因此它们突然与错误的对象相关联。

所以我的问题是,是否有可能对列表进行排序,而不改变其索引。

3 个答案:

答案 0 :(得分:2)

使用Tag属性,只需将对象附加到ListItem即可避免必须处理索引:

for(int i = 0; i < myObjects.Count; i++)
{
    var lItem = new ListBoxItem();
    lItem.Tag = myObjects[i];
    // do some other things...
}

所以稍后你可以这样做:

ListBoxItem li = // again the selected item
MyObject obj = li.Tag as MyObject;

如果您真的想要处理索引,可以将原始索引添加为Tag到您的商品。这样,它们出现的顺序不会干扰您原来的对象顺序。

for(int i = 0; i < myObjects.Count; i++)
{
    var lItem = new ListBoxItem();
    lItem.Tag = i;
    // add other values to your item
}

然后是:

ListBoxItem li = // your selected item
MyObject obj = myObjects[(int)li.Tag];

答案 1 :(得分:2)

为什么不通过索引的值intead进行检查。值始终是您要查找的值。列表框中的索引对应于对象从顶部开始的位置,因此当您对其进行排序时,索引将会更改。

答案 2 :(得分:1)

我更喜欢@ germi的答案,但这里有另一种选择:

  1. 创建一个与字符串列表大小相同的索引数组。
  2. 创建一个字符串副本的数组(这是必要的,因为下一步需要数组而不是列表)
  3. 使用Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items)对字符串和索引进行排序。
  4. 使用列表框的已排序字符串数组。
  5. 当您从列表框中获取索引时,使用它通过已排序的索引数组查找原始索引。
  6. 例如,请考虑以下代码:

    List<string> strings = new List<string>() {"Zero", "One", "Two", "Three", "Four", "Five"};
    
    var stringsArr = strings.ToArray();
    var indices    = Enumerable.Range(0, strings.Count).ToArray();
    
    Array.Sort(stringsArr, indices);
    
    for (int i = 0; i < stringsArr.Length; ++i)
        Console.WriteLine("{0} has original index {1}", stringsArr[i], indices[i]);
    
    // Add stringsArr to the listbox.
    // If an index from the listbox is lbi, then the original index of the item
    // that it refers to will be indices[lbi]
    
相关问题