In my code I’m creating a number of lookup tables.
var Dict1 = data1.ToDictionary(dim => new { dim.Val1,dim.Val2,.. } );
var Dict2 = data2.ToDictionary(dim => new { dim.Val1,dim.Val2,.. } );
sometime there are duplicate key values, so I tried to use a catch block
try
{
var Dict1 = data1.ToDictionary(dim => new { dim.Val1,dim.Val2,.. } );
}
catch (ArgumentException ex)
{
Console.WriteLine("Duplicate values in Data1 {0}",ex);
throw;
}
but this approach means that the Dicts won’t be visible to the rest of the code.
Any ideas on how to do this?
Edit: the intent of the catch block is to report which dictionary creation failed.
Declare and add a single element above the try, and then add the rest inside. Since you’re specifically worried about duplicate keys, adding the first key/item gets you the type without the risk.
EDIT: I think just inferring the type, without adding the first element, is slightly better. While the usage is a bit cumbersome, it’ll make it easier to add remaining elements (as opposed to clearing the dictionary, and then adding – or having to add everything after the 1st one – really only cleanly doable if you’re consuming an IEnumerable).
Or, create a convenience function to catch the exception for you:
The caveat of this is that you can’t call
TryCatch<,>in the “natural” ways:which, since you can’t specify
TResult, forces you into the somewhat odd syntax of declaringTExceptionon the lambda: