使用 IEnumerable> ds 获取键、值对
本文关键字:获取 值对 ds IEnumerable string 使用 object Dictionary | 更新日期: 2023-09-27 18:34:56
我有一个函数的返回类型被设置为IEnumerable<Dictionary<string, object>>
,我需要获取键,值对。
使用适当的键,我需要更改值。
当返回类型是字典时,我有一个解决方案,但在IEnumerable<Dictionary<string, object>>
时没有
我最后需要修改值之后,找到特定的键。
以下这些解决方案可能是您想要的,但是您必须根据您的情况确定哪一个更合适
鉴于
var myKey = "someKey";
假设您的词典列表仅包含您要查找的密钥一次
var aDictionary = MyEnumerable.Single(x => x.ContainsKey(myKey));
aDictionary[myKey] = myNewValue;
如果出现以下情况,将引发无效操作异常
- 找到多个密钥
- 未找到密钥
假设您的词典列表可能包含也可能不包含您要查找的密钥,只有一次
var aDictionary = MyEnumerable.SingleOrDefault(x => x.ContainsKey(myKey));
if(aDictionary != null)
{
aDictionary[myKey] = myNewValue;
}
如果出现以下情况,将引发无效操作异常
- 找到多个密钥
假设您的密钥可能多次出现
foreach (var aDictionary in MyEnumerable.Where(x => x.ContainsKey(myKey)))
{
aDictionary[myKey] = myNewValue;
}
更新
似乎您可能会对类型IEnumerable<Dictionary<string, object>>
感到困惑
IEnumerable
是一个列表(对于此对话的重点(
Dictionary
表示键和值的集合。
所以你有一个键和值的集合列表
您可以使用
foreach句子遍历IEnumerable>:(这只是一个例子来帮助说明(
IEnumerable<Dictionary<string, object>> colectionDict;
foreach(var dict in colectionDict) //dict is an object of type Dictionary<string,object>
此外,还可以使用变量类型枚举器。
var enum = colectionDict.GetEnumerator();
while(enum.Next){
var dict = enum.Current; // dict is an object of type Dictionary<string,object>
}