2012-10-31 32 views
0

我明白为什么没有建在做到这一点的方法,但是我希望有一个集合对象,将允许值枚举过程中改变可能收集像字典<K, V>这使得价值变化

想象一下以下内容:

Dictionary<string, List<string>> test = new Dictionary<string, List<string>> {{"key", null}}; 

可以说我有这20个它实现IEnumberable

类中我想使用拉姆达或简单foreach通过类迭代和发现该对象与某个键匹配,然后使用Value参数存储我的List<T>

+0

您是否尝试过使用ConcurrentDictionary? –

+5

if(test.ContainsKey(“key”))test [“key”] = myList;'?你为什么要枚举它? –

+2

你的意思是20个类似字典的对象,或者20个'string' /'List '对吗?如果是后者,为什么你要遍历这些对,而不是直接通过键访问你想要的那个呢? – Rawling

回答

0

你可能会寻找一个叫做multimap集合。有关我的实施,请参阅here

0

你可以避免使用一个枚举器,例如,

var data = myEnumerable.ToArray(); 
for(var i = 0; i < data.Length; i++) { 
    // here you can manipulate data[i] to your heart's content 
} 
+1

太诗意......;) –

0

当你发现你无法通过Value属性更改DictionaryEntry - 你必须使用Key通过Item访问去了。

一种选择是把你的Where结果到一个数组,然后循环得到匹配Key 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"}; 
+0

但为什么不只是做'if(test.ContainsKey(“key”))test [“key”] = new List {...}'? – Rawling

+0

@Rawling因为OP提到使用Lambda来查找匹配键。如果它只是一个简单的字符串匹配,那么是的,它可以被简化。 –

+0

呃,够公平的。这是一个相当混乱的问题。 – Rawling

0

你可以使用这个字典中的修改值:

public static void ChangeValue(string indexKey,List<string> newValue) 
{ 
    if (test.ContainsKey(indexKey)) 
     keysDictionary[indexKey] = newValue; 
}