Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a specific element from the list of Dictionary

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.

like image 737
Michael Avatar asked Dec 21 '25 00:12

Michael


1 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);
} 
like image 73
Markus Safar Avatar answered Dec 23 '25 03:12

Markus Safar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!