Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 输入值的LinQ_C#_Linq - Fatal编程技术网

C# 输入值的LinQ

C# 输入值的LinQ,c#,linq,C#,Linq,我有以下字典: public Dictionary<string,object> Items; 公共字典项; 现在,我需要获取字典项的值来自特定类型的所有项。(例如“int”) var intValues=Items.OfType根本不起作用 没有LinQ的代码类似于: var intValues=new Dictionary<string,int>() foreach (var oldVal in Items) { if (oldVal.Value is int

我有以下字典:

public Dictionary<string,object> Items;
公共字典项;
现在,我需要获取字典项的来自特定类型的所有项。(例如“int”)

var intValues=Items.OfType
根本不起作用

没有LinQ的代码类似于:

var intValues=new Dictionary<string,int>()
foreach (var oldVal in Items) {
  if (oldVal.Value is int) {
    intValues.add(oldVal.Key, oldVal.Value);
  }
}
var intValues=new Dictionary()
foreach(项目中的var oldVal){
if(oldVal.Value为int){
intValues.add(oldVal.Key,oldVal.Value);
}
}
(更新)我的例子应该说明基本思想。但如果可能的话,我会避免因此而创建一本新词典。

你可以这样做

var result = Items.Where(x => x.Value is int)
                  .ToDictionary(x => x.Key, x => x.Value);

您的
foreach
在LINQ中的直接翻译如下:

var intValues = Items.Where(item => item.Value is int)
                     .ToDictionary(item => item.Key, item => (int)item.Value);
因此,基本上,您首先筛选
项.Value
int
的位置,然后使用将这些值转换为
int
的位置从中创建词典,以确保生成的词典是
词典。由于我们已经筛选了非整数,因此此类型转换将始终成功。

尝试以下操作:

var intValue = Items
    .Where(x => x.Value is int) // filter per Value is int
    .ToDictionary(x => x.Key, x => (int)x.Value); // create a new dictionary converting Value to int

您可以在
属性上使用
is
运算符:

var intValues = Items.Where(x => x.Value is int);
如果您希望在末尾有一个实际的
词典
,只需添加:

.ToDictionary(v=> v.Key, v=> (int)v.Value)