【问题标题】:How can I filter a dictionary using LINQ and return it to a dictionary from the same type如何使用 LINQ 过滤字典并将其返回到相同类型的字典
【发布时间】:2010-10-21 15:13:39
【问题描述】:

我有以下字典:

Dictionary<int,string> dic = new Dictionary<int,string>();
dic[1] = "A";
dic[2] = "B";

我想过滤字典的项目并将结果重新分配给同一个变量:

dic = dic.Where (p => p.Key == 1);

如何将结果作为字典从相同类型返回 [&lt;int,string&gt;]?

我试过ToDictionary,但没用。

【问题讨论】:

  • 以后,如果您尝试了明显的方法但发现它不起作用,请发布您尝试过的代码。

标签: c# linq dictionary linq-to-objects


【解决方案1】:

ToDictionary 是要走的路。它确实工作 - 你只是使用不正确,大概。试试这个:

dic = dic.Where(p => p.Key == 1)
         .ToDictionary(p => p.Key, p => p.Value);

话虽如此,我假设您真的想要一个不同的 Where 过滤器,因为您当前的过滤器只能找到一个键...

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 2016-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 2011-12-24
    • 1970-01-01
    相关资源
    最近更新 更多