![](/img/trans.png)
[英]How to update a c# dictionary where key is set, value is empty in nested foreach loop
[英]C# foreach loop with key value
在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
包含匹配的值。
在.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);
在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
。
您无法直接访问组名称,必须在regex实例上使用GroupNameFromNumber
( 请参阅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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.