【问题标题】:How can you select and filter dictionary keys based on their values using Linq?如何使用 Linq 根据字典键的值选择和过滤字典键?
【发布时间】:2015-11-03 05:32:21
【问题描述】:

给定一个Dictionary<int, double>

如何选择值小于localThreshold 的键?

例如,如果我有:

var someDict = new Dictionary<int, double>() {
    {1, 392.3},
    {2, 612},
    {3, 981} ... };

如果localThreshold 为 400,我想获得值 1(假设没有其他字典值小于 400)。

【问题讨论】:

  • 请看下面的答案。他们提供了一个想法来做我所期望的。

标签: c# linq dictionary


【解决方案1】:
        Dictionary<int, double> d = new Dictionary<int, double>();
        //(1,392.3) , (2, 612),(3,981),(4,344.23)
        d.Add(1, 392.3);
        d.Add(2, 612);
        d.Add(3, 987);
        d.Add(4, 344.23);

        //if(dictionary.Value less than localVar)
        double localVar = 500;
        var res = d.Where(i => i.Value < localVar).Select(j => j.Key);

        foreach(var v in res) Console.WriteLine(v);
        //1
        //4

编辑:我的速度不够快...

【讨论】:

    【解决方案2】:

    给你。 :-)

    示例:如果字典包含 { (1,392.3) , (2, 612),(3,981),(4,344.23)...}

    private IDictionary<int, decimal> myDict = new Dictionary<int,decimal>
    {
        {1, 392.3m},
        {2, 612m},
        {3, 981m},
        {4, 344.23m}
    }
    

    现在我想按条件选择一个键 if(dictionary.Value 小于 localVar) 然后选择该键。

    public int[] GetKeysWhereValueLessThan(decimal value)
    {
        return myDict
            .Where(kv => kv.Value < value)
            .Select(kv => kv.Key)
            .ToArray();
    } 
    

    【讨论】:

      【解决方案3】:

      可以有多个符合条件的值-

      Dictionary<int, decimal> dict = new Dictionary<int,decimal>();
      dict.Add(1, 392.3m); 
      dict.Add(2, 612m); 
      dict.Add(3, 981m); 
      dict.Add(4, 344.23m);
      List<int> Result = dict.Where(x => x.Value < 400).Select(x => x.Key).ToList();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 2020-02-06
        • 1970-01-01
        • 2015-05-17
        • 1970-01-01
        • 2010-11-15
        • 1970-01-01
        相关资源
        最近更新 更多