这只是一个好奇的问题,我想知道是否有人有一个很好的答案:
在.NET Framework类库中,我们有两个方法:
public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate
)
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
Run Code Online (Sandbox Code Playgroud)
他们为什么用Func<TSource, bool>而不是Predicate<TSource>?好像Predicate<TSource>只由List<T>和Array<T>,而Func<TSource, bool>所使用的几乎所有Queryable和Enumerable方法和扩展方法...什么与怎么了?
将一些项目(不是全部)从一个列表转移到另一个列表的最佳方式是什么.
我正在做的是以下内容:
var selected = from item in items
where item.something > 10
select item;
otherList.AddRange(selected);
items.RemoveAll(item => selected.Contains(item));
Run Code Online (Sandbox Code Playgroud)
为了获得最快/最好的代码,还有更好的方法吗?
基本上,我试图做这个,但我不知道T将是什么,所以我使用的反思和表达式树构建东西.
// Input (I don't know about "Book")
Type itemType = typeof(Book);
// Actual Code
// Build up func p => p.AuthorName == "Jon Skeet"
ParameterExpression predParam = Expression.Parameter(itemType, "p");
Expression left = Expression.Field(predParam, itemType.GetField("AuthorName"));
Expression right = Expression.Constant("Jon Skeet", typeof(string));
Expression equality = Expression.Equal(left, right);
Delegate myDelegate = Expression.Lambda(equality, new ParameterExpression[] { predParam }).Compile(); // Not sure if I need this
// Build up predicate type (Predicate<Book>)
Type genericPredicateType = typeof(Predicate<>);
Type constructedPredicateType = genericPredicateType.MakeGenericType(new Type[] { …Run Code Online (Sandbox Code Playgroud) 我很难理解为什么List<T>FindAll(...)方法不接受Func<TSource, bool>,而是坚持接受Predicate<TSource>.
因此,当我有一List本书时,我只想获得比10便宜的书.这个代码运行得很好.
Predicate<Book> CheapBooksPredicate = b => b.Price < 10;
var cheapBooksPredicate = books.FindAll(CheapBooksPredicate);
Run Code Online (Sandbox Code Playgroud)
但是当我换Predicate<TSource>到Func<TSource, bool>
Func<Book, bool> CheapBooksFunc = b => b.Price < 10;
var cheapBooksFunc = books.FindAll(CheapBooksFunc);
Run Code Online (Sandbox Code Playgroud)
我收到错误:
参数1:无法从'System.Func'转换为'System.Predicate'
我在这里失踪了什么?当两个Func<TSource, bool>和Predicate<TSource>的predicates.Predicate<TSource>应该是a的专用版本,Func它根据一组条件获取和计算一个值并返回一个布尔值,因此我可以在使用方面相互替换它们.