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

Resharper always asks me to change the foreach loops in linq, and I try. It guarded 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); } } 

fileEnvironment returned as an object from the configuration section. This is the reason for the broadcast.

+6
source share
1 answer

You can use the OfType operator:

Filters IEnumerable elements based on the specified type.

 foreach(var element in fileEnvironmentSection.FileEnvironmentList .OfType<FileEnvironmentElement>()) { result.Add(element.Key, element.Value); } 

LINQ is not going to help with the body of the loop, as it mutates an existing dictionary. LINQ is typically used to create new data, not to modify existing data.

If you do not mind returning a new dictionary, you can do:

 var newResult = fileEnvironmentSection.FileEnvironmentList .OfType<FileEnvironmentElement>() .ToDictionary(element => element.Key, element => element.Value); 
+10
source

Source: https://habr.com/ru/post/906566/


All Articles