【问题标题】:Removing specific values from a Dictionary C# with Linq使用 Linq 从 Dictionary C# 中删除特定值
【发布时间】:2016-10-07 10:19:23
【问题描述】:

我有一本字典,其中包含来自已解析测试运行的信息。键是方法的名称,值是TestRunProperties 的列表。我的字典包含来自测试运行的所有方法,我想删除在测试运行期间失败的方法。这可能与Linq有关吗?

TestRunProperties 类:

public class TestRunProperties
{
    public string computerName { get; set; }
    public TimeSpan duration { get; set; }
    public string startTime { get; set; }
    public string endTime { get; set; }
    public string testName { get; set; }
    public string outcome { get; set; }
}

字典:

//Key is the name of the method, value is the properties associated with each run
private static Dictionary<string, List<TestRunProperties>> runResults = new Dictionary<string, List<TestRunProperties>>();

我已经尝试过了,但我认为我对 Where 部分感到困惑:

runResults.Remove(runResults.Where(methodName => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed"))));

我对 Linq 和 Lambda 还很陌生,我仍在尝试了解如何访问这样的数据。

【问题讨论】:

  • 感谢大家的帮助,所有的答案都非常棒!

标签: c# linq dictionary lambda


【解决方案1】:

只需使用循环删除您不想要的项目。可以写一个扩展方法,方便调用:

public static class DictionaryExt
{
    public static void RemoveAll<K, V>(this IDictionary<K, V> dict, Func<K, V, bool> predicate)
    {
        foreach (var key in dict.Keys.ToArray().Where(key => predicate(key, dict[key])))
            dict.Remove(key);
    }
}

这通常比创建一个全新的字典更有效,尤其是当要删除的项目数量与字典的大小相比相对较少时。

您的调用代码如下所示:

runResults.RemoveAll((key, methodName) => methodName.Value.Where(method => method.outcome.ToLower().Equals("failed")));

(我选择了名字RemoveAll()来匹配List.RemoveAll()。)

【讨论】:

    【解决方案2】:

    您可以通过过滤掉无效的字典来创建一个新字典:

    var filtered = runResults.ToDictionary(p => p.Key, p => p.Value.Where(m => m.outcome.ToLower() != "failed").ToList());
    

    好的,grrrrrrr 更快:-)

    【讨论】:

    • 谢谢你这已经奏效了! grrrrrr 答案很接近,但错过了一两点:)
    【解决方案3】:

    说实话,您最好从现有字典中选择一本新字典:

    runResults.Select().ToDictionary(x => x.Key, x => x.Value.Where(x => x.Value.outcome != "failed"));
    

    *编辑以反映字典中的列表。

    实际上,你也可以通过这样做来摆脱那些没有成功的结果:

    runResults.Select(x => new { x.Key, x.Value.Where(x => x.Value.outcome != "failed")} ).Where(x => x.Value.Any()).ToDictionary(x => x.Key, x => x.Value);
    

    【讨论】:

    • 我认为上面缺少了一部分;值是一个列表而不是一个单独的 TestRunProperty,所​​以我无法从中访问 .outcome
    • 啊,所以你只需要再向下查询一级
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多