【问题标题】:C# Dictionary Loop Through Only Certain Datasets [duplicate]C#字典循环仅通过某些数据集[重复]
【发布时间】:2019-03-11 20:01:37
【问题描述】:

假设我有一个字典wipProfile,其定义为:

Dictionary<string, int> wipProfile = new Dictionary<string, int>() { { "L1", 10 }, { "L2", 12 }, { "L3", 23 }, { "L4", 9 } };

我想知道如何只遍历那些值 >= 10 的对象?

我知道我可以这样做:

foreach (KeyValuePair<string, int> lot in wipProfile)
{
        if (lot.Value >= 10)
        {
            //Do something here.
        }
}

但是有没有办法在进入循环之前指定过滤条件,这样我就不需要遍历整个字典了,这样说:

foreach (KeyValuePair<string, int> lot in wipProfile where lot.Value >= 10){
    //...
}

【问题讨论】:

  • 那么,您认为foreach 和您对so that I don't need to iterate through the entire dictionary 的想法有什么区别?
  • @RandRandom 主要是更简化的代码。而且我只能处理那些我真正关心的人。

标签: c# loops dictionary foreach


【解决方案1】:

试试这个,使用System.Linq

foreach (KeyValuePair<string, int> lot in wipProfile.Where(kv => kv.Value >= 10))
{
    //...
}

【讨论】:

    【解决方案2】:

    你正在寻找这样的东西:

     wipProfile.Where((key, value) => value > 10).ToList();
    

    这将为您提供在线过滤值大于 10 的项目的列表。然后您可以使用 Linq 样式或使用显示的保留字执行 ForEach!

    编辑:

    正如 Steward 所说,正确的做法是这样的:

     wipProfile.Where(keyValuePair => keyValuePair.Value > 10).ToList();
    

    【讨论】:

    • OP 想要大于 10 的值,您的过滤基于大于 10 的索引。
    • 我认为你在评论错误的答案老兄。我的解决方案是使用字典的值进行过滤。 Aotn 解决方案是使用索引。如果您是这样做的人,请删除减号,因为这行得通。
    • 您在代码中使用Where 的重载,它有一个KeyValuePair 和一个索引,value 是元素的索引而不是KeyValuePair 的值。
    • 你是对的管家。对不起。会在下面编辑它以防万一并给你信用。
    猜你喜欢
    • 2015-12-29
    • 2012-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    相关资源
    最近更新 更多