c# - 这个foreach中间有个cast,能翻译成linq吗?

标签 c# linq

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 作为配置部分的对象返回。这就是 Actor 阵容的原因。

最佳答案

您可以使用 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 不会对循环主体提供帮助,因为它正在改变现有字典 - LINQ 通常用于创建新数据而不是修改现有数据.

如果你不介意在这里返回一本新词典,你可以这样做:

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

关于c# - 这个foreach中间有个cast,能翻译成linq吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8957255/

相关文章:

c# - Fluent NHibernate 自动映射 : Alter DateTime to Timestamp

c# - WPF:KeyboardNavigationMode.Contained 无法抑制焦点环绕

c# - Entity Framework 在传递谓词时返回不同的结果

c# - 林克扩展。更改源列表中的属性值

c# - 无法从票证集合中选择最新的票证

c# - 三元最佳实践

C# Mongodb 将 List<BsonDocument> 合并为单个 BsonArray

c# 在应用程序中添加一个 PayPal 捐赠按钮

c# - GetHashCode() 方法是否应该注意作为参数给出的空值?

c# - 转换为自定义类型、Enumerable.Cast<T> 和 as 关键字