带有键值的C#foreach循环

Unk*_*ech 11 c# regex loops

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

foreach($array as $key => $value)
Run Code Online (Sandbox Code Playgroud)

我有以下代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

//here我想,match.add(key, value)但我无法弄清楚如何从GroupCollection获取密钥,在这种情况下应该是捕获组的名称.我知道那里gc["goupName"].Value包含了比赛的价值.

Mar*_*ell 10

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

// outside all of the loops
string[] groupNames = regex.GetGroupNames();
Run Code Online (Sandbox Code Playgroud)

然后你可以根据这个迭代:

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

或者如果你想使用LINQ:

var match = groupNames.ToDictionary(
            groupName => groupName, groupName => gc[groupName].Value);
Run Code Online (Sandbox Code Playgroud)