Resharper is always asking me to change foreach loops into linq, and I try to. This one stumped me.
foreach(var fileEnvironment in fileEnvironmentSection.FileEnvironmentList) {
var element = fileEnvironment as FileEnvironmentElement;
if(element == null) {
//Not the expected type, so nothing to do
} else {
//Have the expected type, so add it to the dictionary
result.Add(element.Key, element.Value);
}
}
The fileEnvironment is returned as an object from the configuration section. That’s the reason for the cast.
You can use the
OfTypeoperator:LINQ isn’t going to help with the body of the loop since it’s mutating an existing dictionary – LINQ is normally used for creating new data rather than modifying existing data.
If you don’t mind returning a new dictionary here, you could do: