Removing Null Values from a Dictionary with LINQ

Removing Null Values from a Dictionary with LINQ

Christopher Kaukis
//

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);

Related

Need Expert Help?

See Our Full Menu of Data Services

InterWorks uses cookies to allow us to better understand how the site is used. By continuing to use this site, you consent to this policy. Review Policy OK

×

Interworks GmbH
Ratinger Straße 9
40213 Düsseldorf
Germany
Geschäftsführer: Mel Stephenson

Kontaktaufnahme: markus@interworks.eu
Telefon: +49 (0)211 5408 5301

Amtsgericht Düsseldorf HRB 79752
UstldNr: DE 313 353 072

×

Love our blog? You should see our emails. Sign up for our newsletter!