简体   繁体   English

使用Linq从C#中的字典中删除具有相同值数据的多个键

[英]Remove multiple keys with same value data from dictionary in C# using Linq

I know there has to be a better way to do this... maybe with LINQ? 我知道必须有一个更好的方法来执行此操作……也许使用LINQ? If I remove a value, it invalidates the iterator which is why I have this inside of an infinite loop which starts the process all over again. 如果我删除一个值,它将使迭代器无效,这就是为什么我将其置于无限循环内的原因,该循环将重新开始整个过程​​。 I'm looking for a way to do this that is easier to read, maintain and ultimately much faster. 我正在寻找一种做到这一点的方法,该方法更易于阅读,维护并最终更快。 Here's what I got: 这是我得到的:

Dictionary<string, string> Channels = //...;
while (true)
{
    var bFound = false;
    foreach(var c in Channels)
    {
        if(c.Value == version)
        {
            Channels.Remove(c.Key);
            bFound = true;
            break;
        }
    }
    if (!bFound) { break; }
}

Thanks for any help in optimizing this routine. 感谢您对优化此例程的任何帮助。

Based on your example it appears you are removing based on comparison with version value. 根据您的示例,您似乎正在根据与版本值的比较进行删除。

Channels = Channels.Where(x=> x.Value != version)
              .ToDictionary(c => c.Key, c => c.Value);

I'm looking for a way to do this that is easier to read, maintain and ultimately much faster 我正在寻找一种更容易阅读,维护并最终更快的方法

Just use the code below: 只需使用以下代码:

var keys = Channels.Keys.ToArray();
foreach(var key in keys)
{
    if(Channels[key] == version)
    {
        Channels.Remove(key);
    }
}

No LINQ needed for simplicity. 无需LINQ即可简化操作。 We traverse the dictionary once for performance. 我们遍历字典一次以提高性能。

If you capture the matches before removing items from the dictionary, your enumerator will not be invalidated. 如果您在从字典中删除项目之前捕获了匹配项,则枚举器不会失效。

List<KeyValuePair<string, string>> matches = Channels
  .Where(kvp => kvp.Value == version)
  .ToList();

foreach(KeyValuePair<string, string> match in matches)
{
  Channels.Remove(match.Key);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM