【问题标题】:Get a filtered Dictionary from a Dictionary using LINQ使用 LINQ 从字典中获取过滤的字典
【发布时间】:2014-04-10 10:43:26
【问题描述】:

我有一个类型为 (string, string) 的字典,它是组及其 ID 的列表。我需要第二本不应该有五组的字典(我知道)。任何人都可以帮助我在 LinQ 中构建选择,我可以用它来创建这个子字典吗?

【问题讨论】:

  • 请显示一些代码。我们没有可以帮助您的上下文。
  • 3 个答案.. 显然我是唯一一个无法理解您的问题的人。我道歉......我想?

标签: c# .net linq dictionary


【解决方案1】:
var myDic = new Dictionary<string,string>();
myDic.Add("1","One");
myDic.Add("2","Two");
myDic.Add("3","Three");
myDic.Add("4","Four");
//myDic.Dump();

var exclusions = new []{"2","3"};
var newDict = myDic.Where(x=> !exclusions.Contains(x.Key))
     .ToDictionary(x=> x.Key, x=> x.Value);
//newDict.Dump();

【讨论】:

  • 哈! LINQPad 怪胎! :)
  • 非常感谢。找到了我的答案。
【解决方案2】:
        var groups = new List<string>();
        // Fill your groups
        var yourDict = new Dictionary<string, string>();
        //fill your dict.
        var filteredDict = yourDict.Where(a => !groups.Contains(a.Key)).ToDictionary(k=>k.Key,v=>v.Value);

【讨论】:

    【解决方案3】:

    我认为这应该是诀窍:

    Dictionary<string, string> myDic;
    
    ...
    
    var badGroups = new[] { "badGroup1", "badGroup2", ... };
    
    var my2ndDic = myDic
        .Where(e => !badGroups.Contains(e.Key))
        .ToDictionary(e => e.Key, e.Value);
    

    我想你错过的是.ToDictionary() 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-07
      • 1970-01-01
      相关资源
      最近更新 更多