首页 > 解决方案 > 如何使用参数中的函数作为过滤器?

问题描述

我想从接口调用这个函数。

ICollection<Store> GetStores(Func<Store, bool> filter, bool includeCustomers = false);

你会怎么称呼它?它需要一个过滤功能,我不知道如何使用。

var returnStores = IRepository.GetStores(/*what to write here*/);

例如要查找具有 storeID 的商店:

public class Store
{
  public int StoreId { get; set; }
  public string CountryCode { get; set; }
  public ICollection<Customer> Customers { get; set; }
}

标签: c#

解决方案


您可以传入与所需签名匹配的现有方法的名称:接收 aStore并返回布尔值的方法。

否则,您可以像这样传递匿名函数:

var returnStores = IRepository.GetStores(store => store.Id == 42);

匿名函数接收 aStoretrue仅在其Id为 42 时返回。这只是一个示例,关键是lambda 必须返回一个 bool


推荐阅读