【问题标题】:C#: Retrieve all the keys from a dictionary that match a criteriaC#:从匹配条件的字典中检索所有键
【发布时间】:2016-08-16 20:13:14
【问题描述】:

.net 4.5.2

我的字典是这样定义的:

Dictionary<string, string> Dates = new Dictionary<string, string>();

它包含这种格式的键:

2016/4/23
2016/4/24
2016/4/25
2016/4/26
2016/3/1
2016/3/2

如何遍历字典中具有这种格式的所有键:

2016/4/*

【问题讨论】:

  • 如果您发布一些您尝试过的代码,那就太好了。
  • 你可以做foreach(var key in Dates.Keys)
  • 是的,我可以这样做,但我正在寻找可以用于这些情况的 C# 中的一些功能。诸如用于选择性搜索和匹配的 LINQ 之类的东西

标签: c# dictionary pattern-matching iteration


【解决方案1】:

不知道你用的是什么String类型的日期而不是DateTime类型。

无论如何,要回答您的问题,只需使用 StartsWith 扩展方法,如下所示:

var aprilMonthKeys = Dates.Keys.Where(k => k.StartsWith("2016/4/"));

【讨论】:

    【解决方案2】:

    使用

    foreach(var record in Dates.Where(r => r.Key.Contains("2016/4/")))
    {
        // Do something.....
    }
    

    【讨论】:

      【解决方案3】:

      您可以遍历所有项目,检查键是否包含子字符串“2016/4/”并将键保存在另一个列表中。

      List<string> keys= new List<string>();
      
      foreach(var item in Dates)
      {
          if (item.Key.Contains("2016/4/")
              keys.Add(item.Key);
      }
      

      【讨论】:

        【解决方案4】:

        如果你想过滤指定年份和月份的字典,那么你可以这样做:

        var filteredDates =  Dates.Where(d =>
                        DateTime.ParseExact(d.Key, "yyyy/MM/dd", CultureInfo.InvariantCulture).Year == 2016 &&
                        DateTime.ParseExact(d.Key, "yyyy/MM/dd", CultureInfo.InvariantCulture).Month == 4).ToDictionary(d=>d.Key);
        

        这将为您提供包含 2016/04 天数的过滤字典

        【讨论】:

          【解决方案5】:

          如何遍历字典中的所有键

          您可以使用字典的Keys 属性循环遍历每个Key

          foreach(string key in Dates.Keys)
          {
              var date = DateTime.ParseExact(key, "yyyy/M/d", null);
              if(date.Year == 2016 && date.Month == 4)
              {
                   // logic
              }
          }
          

          或者你也可以使用Linq

              var filtered = dictionary.Keys.Where(k=> 
              {           
                  var date = DateTime.ParseExact(k, "yyyy/M/d", null);            
                  return date.Year == 2016 && date.Month == 4;
              });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-10-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-08-26
            • 1970-01-01
            • 2018-12-24
            • 1970-01-01
            相关资源
            最近更新 更多