A common pattern I like to use in C# is one where instead of first checking whether something exists in a collection with Any
then finding it again with First
, I simply call FirstOrDefault
, which both tells me whether it exists and if so, gives me a reference to it:
List<Person> people = ...;
Person found;
if ((found = people.FirstOrDefault(x => x.Age > 10)) != null) {
// Found person with age over 10, and we have them in 'found'
//...
}
This works when the thing being found is a reference type, and can be null. However, I was trying to do the same thing with a Dictionary
's entries:
Dictionary<(int X, int Y), ITileData<(int X, int Y)>> srchField = new();
KeyValuePair<(int X, int Y), ITileData<(int X, int Y)>> next;
while ((next = srchField.FirstOrDefault(x => !x.Value.Reached)) != null) {
// Found next, and we have it in 'next'
//...
}
This, however, doesn't work because srchField.FirstOrDefault(...)
returns a KeyValuePair<TKey, TValue>
, which is a struct. I can work around this by first calling Any
on srchField
, and then calling First
with the same predicate if Any
finds anything, but this is having to do the same search twice. Is there any way I can do the 2-in-1 check existence and store here, only carrying out one search of the dictionary in LINQ?