Resharper总是要求我将foreach循环更改为
linq,我尝试着.这个难倒我.
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作为配置部分中的对象返回.这就是演员阵容的原因.
解决方法
您可以使用
OfType
运算符:
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不会帮助循环体,因为它改变了现有的字典 – LINQ通常用于创建新数据而不是修改现有数据.
如果你不介意在这里返回一个新词典,你可以这样做:
var newResult = fileEnvironmentSection.FileEnvironmentList .OfType<FileEnvironmentElement>() .ToDictionary(element => element.Key,element => element.Value);