Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if KeyValuePair exists with LINQ's FirstOrDefault

Tags:

c#

null

linq

I have a dictionary of type

Dictionary<Guid,int> 

I want to return the first instance where a condition is met using

var available = m_AvailableDict.FirstOrDefault(p => p.Value == 0) 

However, how do I check if I'm actually getting back a KeyValuePair? I can't seem to use != or == to check against default(KeyValuePair) without a compiler error. There is a similar thread here that doesn't quite seem to have a solution. I'm actually able to solve my particular problem by getting the key and checking the default of Guid, but I'm curious if there's a good way of doing this with the keyvaluepair. Thanks

like image 495
Steve Avatar asked Apr 27 '09 14:04

Steve


People also ask

What is default for KeyValuePair?

default equals to null. And default(KeyValuePair<T,U>) is an actual KeyValuePair that contains null, null .

Is KeyValuePair immutable?

KeyValuePair is immutable - it's also a value type, so changing the value of the Value property after creating a copy wouldn't help anyway.

What is KeyValuePair C#?

The KeyValuePair class stores a pair of values in a single list with C#. Set KeyValuePair and add elements − var myList = new List<KeyValuePair<string, int>>(); // adding elements myList. Add(new KeyValuePair<string, int>("Laptop", 20)); myList.

What is the default value returned by FirstOrDefault?

The default value for reference and nullable types is null . The FirstOrDefault method does not provide a way to specify a default value. If you want to specify a default value other than default(TSource) , use the DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource) method as described in the Example section.


1 Answers

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.

like image 117
Marc Gravell Avatar answered Sep 27 '22 22:09

Marc Gravell