Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 684
Vaccano Avatar asked Feb 03 '10 03:02

Vaccano


2 Answers

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.

like image 174
Dynami Le Savard Avatar answered Oct 06 '22 01:10

Dynami Le Savard


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()
like image 38
John Boker Avatar answered Oct 06 '22 00:10

John Boker