[英]Cannot convert from IEnumerable<string> to string
我試圖在兩個循環中清除和替換哈希集中的值。
我相信我已經使用了清晰的方法,但是我似乎無法將值添加回HashSet中。
public void ReplaceValues(string s, IEnumerable<string> newValues)
{
foreach(KeyValuePair<string, HashSet<string>> kvp in deps) //deps is a dictionary<string, HashSet<string>>
dictionary[s].Clear();
foreach(KeyValuePair<string, HashSet<string>> kvp in deps)
//cannot figure out one line to replace the values with the new dependents, throws error code here
}
我希望通過清除值然后添加新值將(a,b)形式的kvps替換為(a,c)
我認為您無需遍歷字典即可獲得該對。 當您從輸入參數中獲得鍵時,可以在單行中替換字典項的值,如下所示。
public static void ReplaceValues(string s, IEnumerable<string> newValues)
{
if(dictionary.ContainsKey(s))
dictionary[s] = new HashSet<string>(newValues);
}
在這里嘗試代碼
更新 :如果要持久保留需要替換其值的Hashset的引用,請遍歷newValues中的每個項目並將其清除后將它們添加到現有的HashSet對象中,如下所示-
public static void ReplaceValues(string s, IEnumerable<string> newValues)
{
if(dictionary.ContainsKey(s))
{
dictionary[s].Clear();
foreach(var val in newValues)
dictionary[s].Add(val);
}
}
您可以執行以下操作:
public void ReplaceValues(string s, IEnumerable<string> newValues)
{
if (deps.TryGetValue(s, out var hs)) {
hs.Clear();
foreach (var value in newValues)
{ hs.Add(value); }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.