c# - LinQ ofType in 值

标签 c# linq

我有以下词典:

public Dictionary<string,object> Items;

现在我需要获取字典项的 来自特定类型的所有项。 (例如“int”)

var intValues = Items.OfType<KeyValuePair<string,int>>根本行不通。

没有 LinQ 的代码会是这样的:

var intValues=new Dictionary<string,int>()
foreach (var oldVal in Items) {
  if (oldVal.Value is int) {
    intValues.add(oldVal.Key, oldVal.Value);
  }
}

(更新)我的示例应该展示基本思想。但如果可能的话,我会避免创建一个新的字典。

最佳答案

直接翻译你的foreach在 LINQ 中将是以下内容:

var intValues = Items.Where(item => item.Value is int)
                     .ToDictionary(item => item.Key, item => (int)item.Value);

所以基本上,您首先过滤 item.Value 所在的位置是一个 int ,然后使用 ToDictionary 从中创建字典您将这些值转换为 int 的位置确保生成的字典是 Dictionary<string, int> .由于我们已经过滤了非整数,因此这种类型转换总是会成功。

关于c# - LinQ ofType in 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43611442/

相关文章:

c# - 带有长 where 子句的 Linq

c# 使用 Tuple 对 List<> 进行排序?

c# - 沙盒 AppDomain 中的 SecurityException

c# - 如何从 C++ dll 在 C# 函数中传递大小未知的数组?

c# - 如何在 WPF C# 应用程序中使用 SlimDX

c# - Linq - 按日期分组并选择计数

c# - 使用多个连接将 linq 转换为 lambda

C# 捕获 webbrowser 发出的 http 请求

c# - 将 int 复制到 byte[] 的最简单方法

linq - Linq to Entities中的动态where子句