2011-11-01 65 views
1

我有一个包含CustomerId,CustomerName和其他一些列的客户集合。使用包含参数的列表过滤集合

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

这是I'ver多远了 - 在这个例子中“filteredCustomers”应包含具有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); 

一个客户ID是什么我做错了客户 - 任何帮助,不胜感激。

回答

4

您可以使用:

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)); 
+0

非常好 - 谢谢,里德 –

2
from Customer in Customers 
where customerIDs.Contains(Customer.CustomerId); 
+0

,你可以内联名单:从客户在新的列表 {3,5}。载有(Customer.CustomerId) – drdwilcox

+2

我相信你会需要客户最后一个“选择客户”条款。 – neontapir

+0

是真实的,但他没有选择,所以我省略了它:从Customer列表中删除新列表 {3,5} .Contains(Customer.CustomerId)select Customer; – drdwilcox

1
var filteredCustomers = Customers.Where(x=>customerIds.Contains(x.CustomerId)); 
0
var byCustIds = from d in Customers 
       where customerIDs.Contains(d.CustomerId) 
       select d;