[英]Remove items from a dictionary based on listbox selection
我有一個列表框,用於打印自定義項目類的名稱
public class Item
{
public string @Url { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public Item(string @url, string name, double price)
{
this.Url = url;
this.Name = name;
this.Price = price;
}
public override string ToString()
{
return this.Name;
}
}
我嘗試了普通方法,但是因為我有單選按鈕來對列表框進行排序,所以自從索引更改以來,它就使它混亂了。
例如
//new item is declared
Dictionary<int, Item> itemList = Dictionary<int, Item> { new Item("f.ca", "name1", 33);
new Item("m.ca", "name2", 44); }
//Items added to listbox
for (int v = 0; v < itemList.Count; v++)
{
itemListBox.Items.Add(itemList[v].Name);
}
//start sorting
var priceSort = from item in itemList
orderby item.Value.Price
select new { item.Value.Name, item.Value.Price };
itemListBox.Items.Clear();
foreach (var i in priceSort)
{
itemListBox.Items.Add(i.Name);
}
//end sorting listbox updated
現在,由於創建了新列表,因此創建了新列表,因此僅需要刪除itemlist中的項目。
/* This code is what i thought but SelectedIndex say if on 0 and since the sorted by price */
itemList.Remove(itemListBox.SelectedIndex);
現在的問題是,當items [1]確實是需要刪除的項目時,它試圖刪除items [0]。 有沒有辦法讓我將itemlistbox的字符串與Items詞典的.Name屬性進行比較?
您說過,字典的鍵由字典中的當前項數確定。 如果是這種情況,則必須執行以下操作:
var matches = itemList.Where(x => x.Name == itemListBox.SelectedValue);
if (matches.Any())
{
itemList.Remove(matches.First().Key);
}
但這是緩慢而優雅的。 您確實沒有正確使用Dictionary類。 字典是根據已知鍵值執行快速訪問的理想選擇。 如果您每次都必須搜索密鑰,那么您將失去詞典提供的所有好處。
您也可以使用簡單的List<Item>
來代替,而使用FindIndex
/ RemoveAt
方法:
var index = itemList.FindIndex(x => x.Name == itemListBox.SelectedValue);
if (index != -1)
{
itemList.RemoveAt(index);
}
這並沒有快很多,但是更優雅-列表是專門為支持這種事情而設計的,而不必訴諸Linq。
或者更好的是,使用項目的名稱作為字典鍵:
Dictionary<string, Item> itemList = Dictionary<string, Item>();
itemList.Add("name1", new Item("f.ca", "name1", 33));
itemList.Add("name2", new Item("m.ca", "name2", 44));
...
itemList.Remove(itemListBox.SelectedValue);
這是一個更有效,更優雅的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.