Make sure the dictionary values โ€‹โ€‹contain an element with a specific field value

I have a dictionary

private readonly Dictionary<int, BinaryAssetExtensionDto> _identityMap; 

And I would like to do something like this:

 if(_identityMap.Values.Contains(x => x.extension == extension))... 

This is possible because the previous code does not work.

Now I do it like this:

 var result = _identityMap.Values.ToList().Find(x => x.extension == extension); if (result != null) return result; 
+4
source share
3 answers
 using System.Linq; ... _identityMap.Values.Any(x=>x.extension==extension) 
+7
source
 return _identityMap.Values.FirstOrDefault(x => x.extension == extension); 

This may return null if the condition is not met. If this is not what you want, you can specify a default value:

 return _identityMap.Values.FirstOrDefault(x => x.extension == extension) ?? new BinaryAssetExtensionDto(); 
+3
source

I believe that one of the following actions will be performed for you:

 if (_identityMap.Values.Where(x => x.extension == extension).Count() > 0) { /*...*/ } if (_identityMap.Values.FirstOrDefault(x => x.extension == extension) != null) { /*...*/ } 

There may be other possible alternatives.

+1
source

Source: https://habr.com/ru/post/1302107/


All Articles