简体   繁体   中英

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. 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:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM