Home > Software engineering >  How to remove Item for the dictonary of <string, list<Items>>
How to remove Item for the dictonary of <string, list<Items>>

Time:11-17

I have a dictionary of fruits <string, list<Fruit>> My dictionary is giving below output

Job ID: 1001         items:
                        "Apple"
                        "Mango"
                        "Banana"
                        "Pine Apple"
                        "Orange"

Job ID: 1002         items:
                        "Banana"
                        "Mango"
                        "Pine Apple"
                        "Orange"
                        "Apple"

Job ID: 1003         items:
                        "Apple"
                        "Banana"
                        "Orange"
                        "Pine Apple"
                        "Mango"

Now I want to remove a specific fruit from the list of fruit

for example, I want to remove Apple from the list

foreach(var i in fruitDic)
            {
                foreach(var k in i.Value)
                {
                    // furitName is variable which I want to remove from list
                    if (k.Name == fruitName)
                    {
                        // here I am getting an error
                        k.Value.Remove(fruitName);

                    }
                }
            }

I am getting an error saying: Error CS1503 Argument 1: cannot convert from 'string' to 'Practice.Models.Fruit'

CodePudding user response:

You could use RemoveAll

Removes all the elements that match the conditions defined by the specified predicate.

Given

var dict = new Dictionary<string, List<Fruit>>();

Usage

foreach (var list in dict.Values)
   list.RemoveAll(x => x.Name == "SomeFunkyFruit");
  • Related