linqc#-4.0tryparseout-parameterstrygetvalue

Using TryGetValue() in LINQ?


This code works, but is inefficient because it double-lookups the ignored dictionary. How can I use the dictionary TryGetValue() method in the LINQ statement to make it more efficient?

IDictionary<int, DateTime> records = ...

IDictionary<int, ISet<DateTime>> ignored = ...

var result = from r in records
             where !ignored.ContainsKey(r.Key) ||
             !ignored[r.Key].Contains(r.Value)
             select r;

The problem is I'm not sure how to declare a variable within the LINQ statement to use for the out parameter.


Solution

  • You need to declare the out variable before the query :

    ISet<DateTime> s = null;
    var result = from r in records
                 where !ignored.TryGetValue(r.Key, out s)
                    || !s.Contains(r.Value)
                 select r;
    

    Be careful of side effects if the query isn't evaluated until later, though...