8
Mar 2010

Removing Null Values from a Dictionary with LINQ

comment icon0 comment(s) |

I don't use Linq much, but when I do I'm amazed how awesome and fun it is. Here is a simple way to remove null values (note values, your keys should never be null, ever and if they are something is wrong) from a dictionary.


Dictionary d1 = new Dictionary()
{
    "key1" => "value1",
    "key2" => null,
    "key3" => "value3"
};

Dictionary d2 = (from kv in d1 
    where kv.Value != null
    select kv).ToDictionary(kv => kv.Key, kv => kv.Value);

Subscribe to our Networks

IW on Facebook