The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,602 other followers

anoymyous type trick: Check if KeyValuePair exists with LINQ’s FirstOrDefault – via Stack Overflow

Posted by jpluimers on 2015/08/27

When you have a Dictionary<TKey, TValue>, then LINQ results will get you a enumerables of KeyValuePair<TKey, TValue>.

Since KeyValuePair is a struct, selecting FirstOrDefault will not get you a null, but a default(KeyValuePair<TKey, TValue>) which is a lot harder to handle than null.

Sometimes, being able to get a null out of FirstOrDefault is very useful, so a bit thank you to Marc Gravell for answering this very neat trick:

If you just care about existence, you could use ContainsValue(0) or Any(p => p.Value == 0) instead? Searching by value is unusual for a Dictionary<,>; if you were searching by key, you could use TryGetValue.

One other approach:

       var record = data.Where(p => p.Value == 1)
            .Select(p => new { Key = p.Key, Value = p.Value })
            .FirstOrDefault();

This returns a class – so will be null if not found.

The trick is this portion:

p => new { Key = p.Key, Value = p.Value }

It introduces an anonymous type with two fields: Key and Value. (Note you can introduce any anonymous type here). Since these are classes, FirstOrDefault will return null if nothing was found.

–jeroen

via:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: