0
public static IEnumerable<T> Matches<T>(this IEnumerable<T> source, Expression<Func<T, string>> predicate, string pattern)
{
     if (source == null) throw new ArgumentNullException("source");
     Regex regex = new Regex(pattern);
     var compiledLambda = predicate.Compile();
     foreach (var item in source)
     {
           string value = (string)compiledLambda.Invoke(item);
           if (regex.IsMatch(value))
                yield return item;
     }
}

IEnumerable<User> test1 = this.Context.Set<User>().Where(u => u.FirstName == "PeopleOnTheMoonInLastYear");
// test1.ToList().Count() --> 0

IEnumerable<User> test2 = this.Context.Set<User>().Matches(a => a.FirstName, @"^(PeopleOnTheMoonInLastYear)");
// test2.ToList().Count() --> error ArgumentNullException

How can my method Matches() work better like Where(), ToList() will never throw ArgumentNullException when result is empty:

test2.ToList().Count() --> 0

neihmac
  • 11
  • 2
  • Why do you call the `Expression>` a `predicate`? A predicate is a boolean-valued function. – Enigmativity Sep 29 '16 at 03:51
  • And why are you using an `Expression<>` anyway? You're in `IEnumerable<>` land so compiling an expression is a waste. – Enigmativity Sep 29 '16 at 03:52
  • And finally, I don't get the `ArgumentNullException` on my tests. Can you please post a [mcve] that shows this issue? – Enigmativity Sep 29 '16 at 03:55
  • Thanks @Enigmativity I will put my expect about Matches() later :) I'm sure test1 and test2 "did not have any data" Everything ok when test1.ToList(), but I get error ArgumentNullException when test2.ToList() It's seem to be test1 is empty by Where() and test2 is null by Matches() How can Matches() return empty IEnumerable if regex.IsMatch(value) always FALSE – neihmac Sep 29 '16 at 07:28
  • An empty enumerable is never `null`. You need to provide an example showing how you get `null`. – Enigmativity Sep 29 '16 at 08:13

0 Answers0