【问题标题】:Select all elements from dictionary when the key is contained in the second dictionary当键包含在第二个字典中时,从字典中选择所有元素
【发布时间】:2013-03-18 09:13:24
【问题描述】:

我有两个字典: Dictionary<DateTime, decimal> d1;Dictionary<DateTime, decimal> d2;

我想要两个执行一个 linq 查询以从 d1 中选择 d2..ContainsKey(d1.key); 的所有元素

【问题讨论】:

  • 太棒了!写你的查询怎么样?

标签: c# .net linq dictionary


【解决方案1】:
var results = d1.Where(x => d2.ContainsKey(x.Key)).Select(x => x.Value).ToList();

或者从选定的数据创建另一个字典:

var results = d1.Where(x => d2.ContainsKey(x.Key)).ToDictionary(x => x.Key, x => x.Value);

【讨论】:

    【解决方案2】:

    如果你想要十进制值作为结果:

    IEnumerable<decimal> result = d2.Keys.Intersect(d1.Keys).Select(k => d1[k]);
    

    如果你想从交叉路口得到一本新字典:

    Dictionary<DateTime, decimal> result = d2.Keys.Intersect(d1.Keys)
                                                  .ToDictionary(k => k, k => d1[k]);
    

    【讨论】:

    • 正在等待有人写这个。
    • 我想要键和值,而不仅仅是字典中的值,这是我的问题
    • 如果你删除 Select(k => kd1[k]); ?
    • @gsmida:我假设你只想要值,编辑了我的答案。
    【解决方案3】:
    from rec in d1 where d2.ContainsKey(rec.key) select d1
    

    【讨论】:

      【解决方案4】:

      试试这个:

      var values = d1.Where(kvp => d2.ContainsKey(kvp.Key)).Select(kvp => kvp.Value);
      

      【讨论】:

      • 我想检索字典而不仅仅是值
      【解决方案5】:
      d1.Keys.Intersect(d2.Keys).ToDictionary( x => x, x => d1[x]);
      

      d1.Keys.Where(k => d2.ContainsKey(k)).ToDictionary( x => x, x => d1[x]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 2021-05-25
        • 1970-01-01
        • 2019-08-25
        相关资源
        最近更新 更多