8

Just come across the following line of code and having a hard time finding documentation for it, is it a lambda expression? What does this do?

temp = Regex.Replace(url, REGEX_COOKIE_REPLACE,match => cookie.Values[match.Groups["CookieVar"].Value]);

Specifically interested in the =>.

gotqn
  • 42,737
  • 46
  • 157
  • 243
m.edmondson
  • 30,382
  • 27
  • 123
  • 206
  • It's [this overload](http://msdn.microsoft.com/en-us/library/ht1sxswy.aspx) - that's a lambda, yes, to specify the [MatchEvaluator delegate](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx). – Rup May 17 '11 at 09:21

3 Answers3

9

If you look at the documentation for Replace, the 3rd argument is a MatchEvaluator:

http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx

This is a delegate that takes a Match as an argument and returns the string to replace it with. Your code is defining a MatchEvaluator using a lambda expression:

match => cookie.Values[match.Groups["CookieVar"].Value]

Here, for each match that the Regex finds, a value is being looked up in the cookie.Values dictionary and the result is being used as the replacement.

ColinE
  • 68,894
  • 15
  • 164
  • 232
7
match => cookie.Values[match.Groups["CookieVar"].Value]

is a shortcut to

delegate (Match match)
{
    return cookie.Values[match.Groups["CookieVar"].Value];
}
Zruty
  • 8,377
  • 1
  • 25
  • 31
1

The RegEx.Replace runs the lambda for every match of REGEX_COOKIE_REPLACE in url and "replaces" the match with the lambdas result.

The lambda (or shorthand delegate)

match => cookie.Values[match.Groups["CookieVar"].Value]

uses the Value of the "CookieVar"Group,of theMatch,to look up a substitution in thecookie.Valuescollection. The lookup value replaces the match.

To tell you more about the "CookieVar" group we would need to see an evaluation of REGEX_COOKIE_REPLACE.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
Jodrell
  • 34,946
  • 5
  • 87
  • 124