KeyNotFoundException in Join implementation

Feb 23, 2010 at 1:31 AM

Hello,

One test case you didn't hit in your Join tests is the case where a customer in the customers sequence doesn't have any orders in the order sequence. When this occurs, a KeyNotFoundException is thrown by the Lookup class's indexer, and that exception is unhandled in your code. LINQ handles this case OK. No exception is thrown.

To repro, in your test data, change the second order from:

new Order ( 4, 23.45m )

to:

new Order ( 3, 23.45m )

So that no orders are associated with Steve.

I'm just starting to seriously dive into LINQ, and your code is incredibly helpful. I've been able to build "custom" Where, Select, and OrderBy extension methods since the Framework contains actual iterator types for these operations (instead of relying on compiler generated iterator blocks), and I was able to lift them out of Reflector. Joins get mighty complicated though, and rely heavily on the compiler. I'd love to see the fix for this exception if you can find some time. Do you think its something as simple as a try/catch block in the indexer?

Thanks,

Bob
 

Feb 23, 2010 at 2:26 AM

In the private _Join method, this seems to give us a graceful exit if the Lookup dictionary doesn't contain the specified key. The indexer simply isn't accessed:

foreach (TOuter o in outer)
    foreach (TInner i in innerLookup[outerKeySelector(o)])
        yield return resultSelector(o, i);

becomes:

foreach (TOuter o in outer)
{
    if (innerLookup.Contains(outerKeySelector(o)))
    {
        foreach (TInner i in innerLookup[outerKeySelector(o)])
            yield return resultSelector(o, i);
    }
}

What do you think?