0

I have a lambda expression and I would like to get back the matched value. Here is an example:

if (Keywords.Any(s => sourceString.Contains(" " + s.Trim())))
          return s;
1
  • 1
    you can use First Commented Jul 29, 2014 at 12:03

4 Answers 4

6

Assuming you only want the first matched result (given you are using Any), you can use First / FirstOrDefault with a filter. Given there is a chance that there could be no matches, I would recommend using FirstOrDefault (First would throw an exception in that case).

var matched = Keywords.FirstOrDefault(s => sourceString.Contains(" " + s.Trim()));
Sign up to request clarification or add additional context in comments.

Comments

2
Keywords.First(s => sourceString.Contains(" " + s.Trim()))

Take a look to Single, SingleOrDefault, First or FirstOrDefault extension methods, depending by the behavior you want.

If you want to get the collection of matching items:

Keywords.Where(s => sourceString.Contains(" " + s.Trim())).ToList()

2 Comments

Well you wouldn't want Single / SingleOrDefault here because there is a chance there could be duplicate entries.
Correct! In fact i wrote my example with "First"... but not knowing the start collection i've exposed all the similar methods ;)
1

You can use .First or .FirstOrDefault for this.

But .First will throw an Exception if nothing is found.

var s = Keywords.FirstOrDefault(keyword => sourceString.Contains(" " + keyword .Trim())); 
return s;

Comments

0

How about:

return Keywords.FirstOrDefault(s => sourceString.Contains(" " + s.Trim()));

This returns the match if found and null if it wasn't found.

Beware of doing this against a database though - .Contains will likely translate to an inefficient query using LIKE. Investigate full-text indexing if that's the case.

1 Comment

In most cases, Contains won't even be supported by the provider.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.