Reputation: 6050
I have a String, I wish to use Linq to run a regular expression to cut down my string to a smaller sub-string which matches my reg ex.
My code at the moment gives the error
'char' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'char' could be found
My code :
string variable = result.Name.Select(r => regEx.Match(r.Name).Groups[2].ToString());
Result.Name
is a string contained in a custom class.
What have I done incorrectly? What is wrong with my syntax/understanding ?
Upvotes: 5
Views: 10817
Reputation: 507
This should work...
string result = result.Name.Select(@regEx => Regex.Match(match.Groups[2].ToString(), @regEx));
Upvotes: 0
Reputation: 50114
You're calling Select
on a single string. Select
is treating your string as a series of characters, and so the r
in your lambda expression is a char
.
If you only have a single string you want to pass into your regular expression, and you only want a single match out, then you don't need LINQ at all. Just call
string variable = regEx.Match(result.Name).Groups[2].ToString();
(I'm assuming result.Name
is your single string, based on your example code.)
Upvotes: 2
Reputation: 217313
Are you looking for something like this?
string[] result = Regex.Matches(input, pattern)
.Cast<Match>()
.Select(match => match.Groups[2].Value)
.ToArray();
Upvotes: 20
Reputation: 6814
Shouldn't it be
string variable = result.Select(r => regEx.Match(r.Name).Groups[2].ToString());
if you run Select on the Name field, you are running it on a string which is an array of char
Upvotes: 0