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

本文关键字:数组 where 子句 查找 何添加 添加 | 更新日期: 2023-09-27 18:24:17

我想知道是否可以为以下内容使用数组,而不是编写多个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) && ....

这可能吗?

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

使用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(),它会将所有过滤带入内存(即,不是只传输所需设备,而是通过网络传输所有设备,并在计算机内存中进行过滤)。

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

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