C# 无法从IEnumerable转换为string

C# 无法从IEnumerable转换为string,c#,ienumerable,C#,Ienumerable,我试图在两个循环中清除和替换哈希集中的值 我相信我已经让clear方法正常工作了,但是我似乎无法将值添加回HashSet public void ReplaceValues(string s, IEnumerable<string> newValues) { foreach(KeyValuePair<string, HashSet<string>> kvp in deps) //deps is a dictionary<string, Hash

我试图在两个循环中清除和替换哈希集中的值

我相信我已经让clear方法正常工作了,但是我似乎无法将值添加回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的KVP替换为a、c。我认为您不需要通过字典循环来获得这对KVP。由于您有一个来自输入参数的键,您可以在一行中替换字典项的值,如下所示

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); }
    }
}

您正在调用字典[s]。清除;在foreach里面。不是100%确定你在这里要做什么。您希望字典中包含新值吗?我希望通过清除值,然后添加新值,将形式为a,b的KVP替换为a,c。是的。这是真的,但您假设没有其他内容引用旧值,并且所有内容都只能通过所述字典访问哈希集。@PatrickRoberts同意,刚刚更新了我的答案来解决这个问题。