Title kind of says it all. I just can't seem to find a DictionaryOrDefault
\ ListOrDefault
\ CollectionOrDefault
option.
Is there such a method? If not how do I do this:
MyClass myObject = MyDictionary
.SingleOrDefault(x =>
{
if (x.Value != null)
return (x.Value.Id == sourceField.SrcField.Id);
else
return false;
}).Key;
if there is more than one match? (I am getting an execption because SingleOrDefault is only meant for single results (imagine that!).)
Guess I needed to be clearer (though the where
answers looks good).
I have the above statement. I changed my program so that it does not always return 1 (there can be several values that match one key). That fails so I am looking for a collection to be returned (rather than just one item).
You can use IEnumerable<T>.FirstOrDefault(Func<T, bool> predicate)
if your intention is to return the first one matching the predicate.
Otherwise you're simply looking at the IEnumerable<T>.Where(Func<T, bool> predicate)
linq extension, which will return all elements that match the predicate passed. That will return an empty IEnumerable<T>
if no elements match the predicate, at which point if you really need the value to be null, you can just look if anything is in it.
var res = MyDictionary.Where(x =>
{
if (x.Value != null)
return (x.Value.Id == sourceField.SrcField.Id);
return false;
});
if (!res.Any())
res = null;
Then if you absolutly need to have it as a list, you can just call
res.ToList();
Note that if you're actually manipulating a Dictionary<TKey, TValue>
, res
will contain KeyValuePair<TKey, TValue>
's.
if you do something like
var mylist = obj.Where(x=>x.attr1 == 4);
you can then check if anything was returned using the .Any() method
mylist.Any()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With