Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I Remove items from dictionary using lambda expression

I am not into LINQ solutions,

I am using simple predicat to determine if the key should be removed, For example if the dictionary is construct like Dictionary<int, int>, so how should I remove all the entries with negative data

I am prefer to use the same dictionary, not to create new one, I don't have preformance issues

Is there a way to do it, without using LINQ, but using Lambda expressions?

I didn't want solutions in LINQ because no one is using them in my project, didn't want to be the first.., but because I saw the LINQ solutions look better, I will use them them..

like image 329
Delashmate Avatar asked Apr 10 '11 07:04

Delashmate


3 Answers

The simplest way is probably to create a new dictionary, if that's okay for you:

var newDictionary = oldDictionary.Where(pair => pair.Value >= 0)
                                 .ToDictionary(pair => pair.Key,
                                               pair => pair.Value);

If you have to mutate the existing dictionary (e.g. because several other objects have reference to the same dictionary) you'd need to build a list of keys to remove, then remove them afterwards:

var toRemove = dictionary.Where(pair => pair.Value < 0)
                         .Select(pair => pair.Key)
                         .ToList();

foreach (var key in toRemove)
{
    dictionary.Remove(key);
}

EDIT: I've just noticed the first sentence: "I am not into LINQ solutions". If that means you don't want to use a LINQ solution, here's the by-hand version:

List<int> toRemove = new List<int>();
foreach (KeyValuePair<int, int> pair in dictionary)
{
    if (pair.Value < 0)
    {
        toRemove.Add(pair.Key);
    }
}

foreach (var key in toRemove)
{
    dictionary.Remove(key);
}

... but if you can use LINQ, I'd encourage you do. My second solution is equivalent to the "by-hand" version, but more readable IMO.

like image 111
Jon Skeet Avatar answered Oct 13 '22 11:10

Jon Skeet


By merely using lambda expression:

foreach (var i in myDict.Where(d => (d.Value  < 0 || d.key <0)).ToList() ) 
{
  myDict.Remove(i.Key);
}
like image 12
Kamyar Avatar answered Oct 13 '22 11:10

Kamyar


var toRemove = dict.Keys.Where(predicate).ToArray();
foreach (var key in toRemove) {
    dict.Remove(key);
}
like image 5
thecoop Avatar answered Oct 13 '22 11:10

thecoop