What is the version of the SingleOrDefault collection for the <T> dictionary?

The type name says it all. I just can't find the DictionaryOrDefault\ ListOrDefault\ option CollectionOrDefault.

Is there such a method? If not, how to do it:

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 get execption because SingleOrDefault is only for single results (imagine that!).)


I think I needed to be more clear (although the answers wherelook good).

I have the above statement. I changed my program so that it does not always return 1 (there may be several values ​​corresponding to one key). This fails, so I'm looking for a collection to be returned (and not just one item).

+5
2

IEnumerable<T>.FirstOrDefault(Func<T, bool> predicate), - , .

IEnumerable<T>.Where(Func<T, bool> predicate) linq, , . IEnumerable<T>, , , , , , - .

var res = MyDictionary.Where(x => 
                        { 
                            if (x.Value != null)  
                                return (x.Value.Id == sourceField.SrcField.Id);  

                            return false;  
                        });
if (!res.Any())
    res = null;

, ,

res.ToList();

, Dictionary<TKey, TValue>, res KeyValuePair<TKey, TValue>.

+4

-

var mylist = obj.Where(x=>x.attr1 == 4);

, - .Any()

mylist.Any()
+1

All Articles