简体   繁体   中英

How to remove a value based on a key from a Dictionary<uint, List<uint>>?

This is the errror message I get with the k variable. I have a dictionary in my code in the format of Dictionary<uint, List<uint>> . I want to iterate over the Dictionary and remove items based on the value and not the key initially. Then I want to remove the key once all the values in the key are removed. I am unsure on how to do this.

I used a foreach loop to iterate but it does not seem to work. Can someone give me guidance with a pseudocode on how to do this.

The k is having issues.

The code I used.

List<uint> todel = MyList.Keys.Where(k => k.Contains(Idx)).ToList();
todel.ForEach(k => MyList.Remove(k));

Any help will be appreciated.

"I want to iterate over the Dictionary and remove items based on the value and not the key initially. Then I want to remove the key once all the values in the key are removed."

Here's one way to do it, if I understand correctly:

Dictionary<int, List<int>> source = new Dictionary<int, List<int>>();
source.Add(1, new List<int> { 1, 2, 3, 4, 5});
source.Add(2, new List<int> { 3, 4, 5, 6, 7});
source.Add(3, new List<int> { 6, 7, 8, 9, 10});

foreach (var key in source.Keys.ToList()) // ToList forces a copy so we're not modifying the collection
{
    source[key].RemoveAll(v => v < 6); // or any other criterion

    if (!source[key].Any())
    {
        source.Remove(key);
    }
}

Console.WriteLine("Key count: " + source.Keys.Count());
foreach (var key in source.Keys)
{
    Console.WriteLine("Key: " + key + " Count: " + source[key].Count());
}

Output:

Key count: 2
Key: 2 Count: 2
Key: 3 Count: 5

I guess this is the problematic line:

List<uint> todel = MyList.Keys.Where(k => k.Contains(Idx)).ToList();

Try something like this

List<uint> todel = MyList.Keys.Where(k => k == Idx).ToList();

k is not a list, it is of type uint.

If you want to remove the records value of which contains Idx, then try this

List<uint> todel = MyList.Where(k => k.Value.Contains(Idx)).Select(x => x.Key).ToList();

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