相关疑难解决方法(0)

为什么Func <T,bool>而不是Predicate <T>?

这只是一个好奇的问题,我想知道是否有人有一个很好的答案:

在.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>所使用的几乎所有QueryableEnumerable方法和扩展方法...什么与怎么了?

.net c# predicate func

207
推荐指数
4
解决办法
5万
查看次数

如何将项目从列表移动到C#中的另一个列表?

将一些项目(不是全部)从一个列表转移到另一个列表的最佳方式是什么.

我正在做的是以下内容:

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)

为了获得最快/最好的代码,还有更好的方法吗?

c# linq list

26
推荐指数
4
解决办法
3万
查看次数

使用C#中的反射将func转换为谓词

基本上,我试图做这个,但我不知道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)

c# reflection predicate expression-trees

5
推荐指数
1
解决办法
1935
查看次数

FindAll - Predicate <TSource> vs Func <TSource,bool>

我很难理解为什么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它根据一组条件获取和计算一个值并返回一个布尔值,因此我可以在使用方面相互替换它们.

.net c#

0
推荐指数
1
解决办法
139
查看次数

标签 统计

c# ×4

.net ×2

predicate ×2

expression-trees ×1

func ×1

linq ×1

list ×1

reflection ×1