C# 收藏类词典<;K、 V>;这允许改变价值

C# 收藏类词典<;K、 V>;这允许改变价值,c#,dictionary,C#,Dictionary,我理解为什么没有内置的方法来实现这一点,但是我想要一个集合对象,它允许在枚举过程中可能的值更改 想象一下: Dictionary<string, List<string>> test = new Dictionary<string, List<string>> {{"key", null}}; Dictionary test=newdictionary{{“key”,null}; 假设我在一个实现IEnumberable的类中有20个这样的函

我理解为什么没有内置的方法来实现这一点,但是我想要一个集合对象,它允许在枚举过程中可能的值更改

想象一下:

Dictionary<string, List<string>> test =  new Dictionary<string, List<string>> {{"key", null}};
Dictionary test=newdictionary{{“key”,null};
假设我在一个实现IEnumberable的类中有20个这样的函数


我想使用lambda或简单的
foreach
遍历类并找到与键匹配的对象,然后使用Value参数存储我的
List

您可以避免完全使用枚举器,例如

var data = myEnumerable.ToArray();
for(var i = 0; i < data.Length; i++) {
    // here you can manipulate data[i] to your heart's content
}
var data=myEnumerable.ToArray();
对于(变量i=0;i
正如您所发现的,您无法通过
属性更改
词典条目
——您必须使用
键通过
访问器

一个选项是将
Where
结果转换为数组,然后循环获取匹配的
s:

Dictionary<string, List<string>> test =  new Dictionary<string, List<string>>
                                             {{"key", null}};
test.Add("newKey",null);

var matches = test.Where(di => di.Key == "key").ToArray();

foreach(var di in matches) {
    test[di.Key] = new List<string> {"one","two"};
字典测试=新字典
{{“key”,null};
test.Add(“newKey”,null);
var matches=test.Where(di=>di.Key==“Key”).ToArray();
foreach(匹配中的变量di){
test[di.Key]=新列表{“一”、“二”};

您可能正在查找一个名为的集合。有关它的实现,请参阅。

您可以使用此选项修改字典中的值:

public static void ChangeValue(string indexKey,List<string> newValue)
{
     if (test.ContainsKey(indexKey))
         keysDictionary[indexKey] = newValue;
}
publicstaticvoidchangeValue(stringindexkey,List newValue)
{
if(测试容器(索引键))
KeyDictionary[indexKey]=新值;
}

您是否尝试过使用ConcurrentDictionary?if(test.ContainsKey(“key”)test[“key”)有什么问题=myList;
?为什么要枚举它?你是说20个类似字典的对象,还是20个字符串?如果是后者,为什么要遍历这些对,而不是直接通过键访问所需的对?谢谢大家,Tim我不认为你能像这样编写它,我在找met描述方法:)。是时候考虑在lambda中编写查找部分了!但是为什么不直接做
if(test.ContainsKey(“key”))test[“key”]=newlist{…}
?@Rawling,因为OP提到使用Lambda来查找匹配的键。如果它只是一个简单的字符串匹配,那么是的,它可以被简化。呃,很公平。这是一个相当令人困惑的问题。