Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# foreach loop with key value

Tags:

c#

regex

loops

In PHP I can use a foreach loop such that I have access to both the key and value for example:

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

I have the following code:

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

at //here I'd like to match.add(key, value) but I cannot figure out how to get the key from the GroupCollection, which in this case should be the name of the capturing group. I know that gc["goupName"].Value contains the value of the match.

like image 263
UnkwnTech Avatar asked Feb 28 '10 10:02

UnkwnTech


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language basics?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.


1 Answers

In .NET, the group names are available against the Regex instance:

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

Then you can iterate based on this:

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

Or if you want to use LINQ:

var match = groupNames.ToDictionary(
            groupName => groupName, groupName => gc[groupName].Value);
like image 69
Marc Gravell Avatar answered Oct 19 '22 17:10

Marc Gravell