简体   繁体   English

c# - 如何从字典列表中删除项目?

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

Here is the values I am adding in Dictionary List:-这是我在字典列表中添加的值:-

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

I can delete from Dictionary based on key value:-我可以根据键值从字典中删除:-

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

Here I pass key value (i.ItemId),it deletes an item from dictionary.在这里我传递键值(i.ItemId),它从字典中删除一个项目。 But When I use List of Dictionary, I couldn't delete items from List of Dictionary based on Key Value.但是当我使用字典列表时,我无法根据键值从字典列表中删除项目。

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);
}

Note:- I have only Key value available when I am deleting from List of Dictionary.注意:- 当我从字典列表中删除时,我只有键值可用。

Help will be appreciated.帮助将不胜感激。

Assuming that i.ItemUid is a key:假设 i.ItemUid 是一个键:

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

If instead i.ItemUid is a key-value pair如果 i.ItemUid 是键值对

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

Edit: total number of keys in all dictionaries:编辑:所有字典中的键总数:

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