2013-12-13 52 views
0

我有一個列表框,我從List中填充。字符串是另一個列表中對象的屬性。從列表中選擇一些東西時,我使用索引來選擇相關對象(當然這與索引列表中的名稱相同)。但是,當我排序列表(按名稱)每個字符串的索引更改,所以他們突然與錯誤的對象有關。如何在不更改索引的情況下對列表框進行排序

所以我的問題是,有沒有排序列表的可能性,而不改變其索引。

回答

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]; 
2

你爲什麼不通過索引值這一翻譯檢查。價值永遠是你要找的人。列表框中的索引對應於對象從頂部開始的地方,因此當對它進行排序時,索引將會改變。

1

我喜歡@ germi的答案,但在這裏是一種替代方案:

  1. 創建一個同樣大小的字符串列表的索引數組。
  2. 創建一個字符串副本的數組(這是因爲下一步需要,因爲下一步需要數組而不是列表)
  3. 使用Array.Sort<TKey, TValue>(TKey[] keys, TValue[] items)將字符串和索引一起排序。
  4. 對列表框使用排序後的字符串數組。
  5. 當您從列表框中取回索引時,使用它通過排序的索引數組查找原始索引。

例如,考慮下面的代碼:

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] 
相關問題