具有多个包含的Linq-to-Sql

问题描述 投票:0回答:1

下面的查询是一个具有多个OR条件的简单查询,基本上是查看searchString是否包含在3个字段中的任何一个中:ItemID,ItemID2或ItemDescription。如果searchString是“3/4管道”,它将只返回包含“3/4管道”的记录。我需要它来返回包含“3/4”和“管道”的记录,以便包括诸如“3/4钢管”或“3/4铜管”或“3/4线管”的记录。实质上,结果值需要包含searchString中的两个单词。 “3/4铜”或“铜管”不会退回,因为它们都不包含“3/4”和“管道”。

而且为了增加乐趣,searchString可以包含任意数量的单词。

IEnumerable<Item> query = from item in context.Items
                                  where item.ItemID.ToUpper().Contains(searchString) ||
                                  item.ItemID2.ToUpper().Contains(searchString) ||
                                  item.ItemDesc.ToUpper().Contains(searchString)
                                  orderby item.ItemClassID, item.ItemID ascending
                                  select item;
        return query.ToList();
sql linq linq-to-sql
1个回答
0
投票

显然你的searchString中的分隔符是空格字符。因此,首先需要将searchString拆分为一个字符串数组:

var searchStringList = searchString.Split(' ');

然后,您可以检查任何指定的列是否包含字符串列表中的所有项,例如:

searchStringList.All(x => item.ItemID.ToUpper().Contains(x))

最后它会是这样的:

var searchStringList = searchString.Split(' ');

IEnumerable<Item> query = from item in context.Items
                                  where searchStringList.All(x => item.ItemID.ToUpper().Contains(x)) ||
                                  searchStringList.All(x => item.ItemID2.ToUpper().Contains(x)) ||
                                  searchStringList.All(x => item.ItemDesc.ToUpper().Contains(x))
                                  orderby item.ItemClassID, item.ItemID ascending
                                  select item;
        return query.ToList();

更新 在您的注释中,上面的代码抱怨本地序列(searchStringList)不能在LINQ to SQL中使用。 我可以提出的一个解决方案是使用ToList()首先将所有表记录存入内存,然后对该对象进行搜索。但是,您应该注意它存在性能问题。

var searchStringList = searchString.Split(' ');

IEnumerable<Item> query = from item in context.Items.ToList()
                                  where searchStringList.All(x => item.ItemID.ToUpper().Contains(x)) ||
                                  searchStringList.All(x => item.ItemID2.ToUpper().Contains(x)) ||
                                  searchStringList.All(x => item.ItemDesc.ToUpper().Contains(x))
                                  orderby item.ItemClassID, item.ItemID ascending
                                  select item;
        return query.ToList();
© www.soinside.com 2019 - 2024. All rights reserved.