Is there a way to cast a dictionary i a one-liner and without all the overhead in C# .net 3?
var result = new Dictionary<string, AccessoryVariant>();
foreach (BaseVariant variant in mVariants.Values)
{
result.Add(variant.Id, (AccessoryVariant)variant);
}
return result;
I would like to do something like this:
return (Dictionary<string, AccessoryVariant>)mVariants;
/Sven
Assuming you’re using .NET 3.5 or 4, you can use the
ToDictionarymethod in LINQ:Alternatively:
Or (assuming
mVariantsis already using the Id as the key):Note that you can’t cast the dictionary directly, because assuming
mVariantis aDictionary<string, BaseVariant>, someone could add a non-AccessoryVariant to the dictionary as a value, which would clearly mess up any code which (reasonably) assumed that theDictionary<string, AccessoryVariant>only containedAccessoryVariantvalues.