Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This foreach has a cast in the middle, can it be translated to linq?

Tags:

c#

linq

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.

like image 863
JimBoone Avatar asked Jan 21 '12 22:01

JimBoone


1 Answers

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);
like image 187
Ani Avatar answered Sep 28 '22 06:09

Ani