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 2,977 other subscribers

Archive for August 27th, 2015

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

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.



Posted in .NET, .NET 3.5, .NET 4.0, .NET 4.5, C#, C# 3.0, C# 4.0, C# 5.0, C# 6 (Roslyn), Development, Software Development | Leave a Comment »

%d bloggers like this: