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
我的方法Matches()如何更好地工作,比如Where(),当结果为空时,ToList()永远不会抛出ArgumentNullException:
test2.ToList()。Count() - &gt; 0