如何添加查找值数组的where子句

时间:2013-07-22 11:37:40

标签: c# linq entity-framework

我想知道我是否可以使用下面的数组而不是写多个OR

from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()
                                    where (d.AssetType == "Laptop" || d.AssetType == "Workstation" || d.AssetType == "Mobile" d.AssetType == "Monitor" d.AssetType == "Other Peripheral" || d.AssetType == "Home Printer" || d.AssetType == "Home Router" || d.AssetType == "Removable Device")
                                            (d.Active == 1) && 
                                            (d.Deleted != 1 || d.Deleted == null) && 

如下所示?

string[] arrItems = new string[] { "Laptop", "Workstation", "Mobile" }; etc
where (d.assetType == arrItems) &&
         (d.Active == 1) && ....

可能吗?

2 个答案:

答案 0 :(得分:4)

使用Contains方法:

from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).AsEnumerable()
where arrItems.Contains(d.AssetType) &&  // same as SQL operator IN
      (d.Active == 1) && 
      (d.Deleted != 1 || d.Deleted == null) && 

同样不要使用AsEnumerable()它会将所有过滤带入内存(即,不是仅传输您通过网络传输所有设备所需的设备,而是在计算机内存中过滤它们。)

答案 1 :(得分:0)

是的。你有两种方法可以做到这一点。琐碎的方式:

from d in myQueryable
where (arrItems.Contains(d.assetType)) &&
      (d.Active == 1) && ....

之前方法的问题在于它会检查所有对(x in myEnumerable, y in arrItems),这会导致O(n²)的复杂性

最好的方式,复杂度为O(n)

from d in myQueryable
join arrItem in arrItems on d.AssetType equals arrItem
select d