自定义yield迭代器返回类似Where方法的结果

时间:2016-09-29 02:07:02

标签: c# return where ienumerable yield

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

0 个答案:

没有答案
相关问题