簡體   English   中英

c# - 如何從字典列表中刪除項目?

[英]How to delete an item from List of Dictionary in c#?

這是我在字典列表中添加的值:-

1,1000
2,2000
1,1000
3,3000

我可以根據鍵值從字典中刪除:-

if (i == null)
    return;
var dict = app["ItemList"] as Dictionary<int, int>;
if (dict != null)
    dict.Remove(i.ItemId);

在這里我傳遞鍵值(i.ItemId),它從字典中刪除一個項目。 但是當我使用字典列表時,我無法根據鍵值從字典列表中刪除項目。

if (i == null)
    return;
var dict = app["ItemList"] as List<Dictionary<int, int>>;
if (dict != null)
{
    var itemDict = new Dictionary<int, int>();
    itemDict[i.ItemUid] = 0;
    dict.Remove(itemDict);
}

注意:- 當我從字典列表中刪除時,我只有鍵值可用。

幫助將不勝感激。

假設 i.ItemUid 是一個鍵:

var dict = app["ItemList"] as List<Dictionary<int, int>>;
if (dict != null)
{
    foreach (var x in dict) x.Remove(i.ItemUid);
}

如果 i.ItemUid 是鍵值對

var dict = app["ItemList"] as List<Dictionary<int, int>>;
if (dict != null)
{
    foreach (var x in dict) x.Remove(i.ItemUid.Key);
}

編輯:所有字典中的鍵總數:

int totalNumberOfKeys = 0;
foreach (var x in dict) totalNumberOfKeys += x.Count;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM