Check if values of Dictionary contains an element with certain field value
I have a Dictionary
private readonly Dictionary<int, BinaryAssetExtensionDto> _identityMap;
开发者_如何学C
And I would like to do something like this:
if(_identityMap.Values.Contains(x => x.extension == extension))...
Is this possible because previous code doesn't work.
Now I'm doing it like this:
var result = _identityMap.Values.ToList().Find(x => x.extension == extension);
if (result != null) return result;
using System.Linq;
...
_identityMap.Values.Any(x=>x.extension==extension)
return _identityMap.Values.FirstOrDefault(x => x.extension == extension);
This may return null if the condition is not satisfied. If this is not what you want you may provide a default value:
return _identityMap.Values.FirstOrDefault(x => x.extension == extension) ??
new BinaryAssetExtensionDto();
I believe that either of the following would work for you:
if (_identityMap.Values.Where(x => x.extension == extension).Count() > 0) { /*...*/ }
if (_identityMap.Values.FirstOrDefault(x => x.extension == extension) != null) { /*...*/ }
There are probably other possible alternatives too
精彩评论