Skip to main content
 首页 » 编程设计

c#之使用包含参数的列表过滤集合

2024年01月25日21dudu

我有一个包含 CustomerId、CustomerName 和其他一些列的 Customers 集合。

我正在传递一个 ID 列表来过滤集合。

这就是我得到的结果 - 在此示例中,“filteredCustomers”应该包含 customerId 为 3 或 5 的客户。

List<int> customerIds = new List<int>(); 
customerIds.Add(3); 
customerIds.Add(5); 
 
var filteredCustomers = from Customer in Customers.Where(x=>x.CustomerId).Contains(customerIds); 

我做错了什么 - 非常感谢任何帮助。

乔

请您参考如下方法:

您可以使用:

var filteredCustomers = Customers.Where(x => customerIds.Contains(x.CustomerId)); 

但是,我强烈建议使用 HashSet<T>而不是 List<T>为此,因为它将使 Contains如果您将来添加更多数字,检查速度会大大加快。这看起来像:

var customerIds = new HashSet<int>(); 
customerIds.Add(3); 
customerIds.Add(5); 
 
var filteredCustomers = Customers.Where(x => customerIds.Contains(x.CustomerId));