【问题标题】:C# foreach loop with key value带有键值的 C# foreach 循环
【发布时间】:2010-02-28 10:04:48
【问题描述】:

在 PHP 中,我可以使用 foreach 循环,这样我就可以访问键和值,例如:

foreach($array as $key => $value)

我有以下代码:

Regex regex = new Regex(pattern);
MatchCollection mc = regex.Matches(haystack);
for (int i = 0; i < mc.Count; i++)
{
     GroupCollection gc = mc[i].Groups;
     Dictionary<string, string> match = new Dictionary<string, string>();
     for (int j = 0; j < gc.Count; j++)
     {
        //here
     }
     this.matches.Add(i, match);
}

//here 我想match.add(key, value) 但我不知道如何从 GroupCollection 中获取密钥,在这种情况下应该是捕获组的名称。我知道gc["goupName"].Value 包含匹配的值。

【问题讨论】:

  • 哪个是key,哪个是value?

标签: c# regex loops


【解决方案1】:

在 .NET 中,组名可用于 Regex 实例:

// outside all of the loops
string[] groupNames = regex.GetGroupNames();

那么就可以根据这个进行迭代了:

Dictionary<string, string> match = new Dictionary<string, string>();
foreach(string groupName in groupNames) {
    match.Add(groupName, gc[groupName].Value);
}

或者如果你想使用 LINQ:

var match = groupNames.ToDictionary(
            groupName => groupName, groupName => gc[groupName].Value);

【讨论】:

    【解决方案2】:

    在 C# 3 中,您也可以使用 LINQ 来进行这种收集处理。使用正则表达式的类仅实现非泛型IEnumerable,因此您需要指定几个类型,但它仍然非常优雅。

    以下代码为您提供了一个字典集合,其中包含作为键的组名和作为值的匹配值。它使用 Marc 的建议使用ToDictionary,只是它指定组名作为键(我认为 Marc 的代码使用匹配值作为键,组名作为值)。

    Regex regex = new Regex(pattern);
    var q =
      from Match mci in regex.Matches(haystack)
      select regex.GetGroupNames().ToDictionary(
        name => name, name => mci.Groups[name].Value);
    

    然后您可以将结果分配给您的this.matches

    【讨论】:

      【解决方案3】:

      您不能直接访问组名,必须在正则表达式实例上使用GroupNameFromNumber (see doc)。

      Regex regex = new Regex(pattern);
      MatchCollection mc = regex.Matches(haystack);
      for (int i = 0; i < mc.Count; i++)
      {
           GroupCollection gc = mc[i].Groups;
           Dictionary<string, string> match = new Dictionary<string, string>();
           for (int j = 0; j < gc.Count; j++)
           {
              match.Add(regex.GroupNameFromNumber(j), gc[j].Value);
           }
           this.matches.Add(i, match);
      }
      

      【讨论】:

        猜你喜欢
        • 2010-12-22
        • 2012-06-22
        • 2012-05-08
        • 2015-06-16
        • 1970-01-01
        • 1970-01-01
        • 2017-02-28
        • 1970-01-01
        • 2016-12-31
        相关资源
        最近更新 更多