2010-02-28 200 views
11

在PHP我可以使用foreach循環,使得我能夠訪問例如鍵和值既:C#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包含匹配的值。

+0

哪個是關鍵,哪個是價值? – kennytm 2010-02-28 10:09:23

回答

10

在.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); 
3

您不能直接訪問組名,hou必須在正則表達式實例(see doc)上使用GroupNameFromNumber

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); 
} 
4

在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

+0

@Tomas - 固定的;好點。 – 2010-02-28 10:42:56