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 OfType operator:
Filters the elements of an IEnumerable based on a specified type.
foreach(var element in fileEnvironmentSection.FileEnvironmentList
                                             .OfType<FileEnvironmentElement>())
{
    result.Add(element.Key, element.Value);
}
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:
var newResult = fileEnvironmentSection.FileEnvironmentList
                                      .OfType<FileEnvironmentElement>()
                                      .ToDictionary(element => element.Key,
                                                    element => element.Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With