views:

42

answers:

1

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.

A: 

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

Thomas Levesque
This works. I'm guessing make sure you evaluate it while the variable is still in scope, and don't try to use it with parallel LINQ.
Joe Daley
@Joe, precisely... that would have unpredictable effects
Thomas Levesque