How to remove a specific element from the list of Dictionary

Viewed 416

I have a Dictionary

Dictionary <String, List<Object>> myDictionary;

What is the best way to update Dictionary so that one of the Object from the list will be removed by known key. For instance I want to remove third object from the list.
Remove will remove value by specific key. So it will remove the whole list corresponding to the key. And I want to update the list that is inside of the dictionary.

2 Answers

You can use the Remove Method.

myDictionary.Remove("key");

According to the documentation the method returns:

true if the element is successfully found and removed; otherwise, false. This method returns false if key is not found in the Dictionary.

Update:

According to your updated question, you want to remove an element within the list which would mean getting the value of the dictionary first, afterwards changing an element within that value (which is a list in your case). So you can use the RemoveAt method of the list there.

List<Object> values;

if (myDictionary.TryGetValue("key", out values))
{
  // Here you have access to the list by using values, therefore you can modify your list here
  // Make sure, that the list really contains an element at index 3
  if (values.Count > 3)
      values.RemoveAt(3);
} 

update Dictionary so that one of the Object from the list will be removed?

First you need to retrieve the List from the dictionary, for example you can use the key. It would be something like:

if (myDictionary.TryGetValue("key", out List<Object> value)) {
  value.RemoveAt(2);
}

You can use TryGetValue to get the value based on your key (and if it exists, then you can get the List<object> reference.

Since the reference for value in the above example is the same reference the Dictariony<> uses, you can use List.RemoveAt(Int32) to remove the 3rd on from the list.

Related