Using contains() in LINQ to SQL(在 LINQ to SQL 中使用 contains())
问题描述
我正在尝试使用 linq-to-sql 在应用程序中实现一个非常基本的关键字搜索.我的搜索词在一个字符串数组中,每个数组项都是一个词,我想找到包含搜索词的行.我不介意它们包含的不仅仅是搜索词(很可能会),但所有搜索词都必须存在.
I'm trying to implement a very basic keyword search in an application using linq-to-sql. My search terms are in an array of strings, each array item being one word, and I would like to find the rows that contain the search terms. I don't mind if they contain more than just the search terms (most likely, they will), but all the search terms do have to be present.
理想情况下,我想要类似于以下代码段的内容,但我知道这行不通.另外,我在这里查看了这个问题,但该问题的作者似乎满足于以相反的方式做事( query.Contains(part.partName) ),这对我不起作用.
Ideally, I would like something similar to the snippet below, but I know that this won't work. Also, I have looked at this question here, but the author of that question seems content to do things the other way round ( query.Contains(part.partName) ), which doesn't work for me.
public IQueryable<Part> SearchForParts(string[] query)
{
return from part in db.Parts
where part.partName.Contains(query)
select part;
}
我怎样才能重写这个查询,使它能够满足我的需要?
How can I rewrite this query so that it will do what I need?
推荐答案
看到其他尝试让我很难过 :(
Looking at the other attempts saddens me :(
public IQueryable<Part> SearchForParts(string[] query)
{
var q = db.Parts.AsQueryable();
foreach (var qs in query)
{
var likestr = string.Format("%{0}%", qs);
q = q.Where(x => SqlMethods.Like(x.partName, likestr));
}
return q;
}
假设:
partName 看起来像:ABC 123 XYZ"
partName looks like: "ABC 123 XYZ"
查询是 { "ABC", "123", "XY" }
query is { "ABC", "123", "XY" }
这篇关于在 LINQ to SQL 中使用 contains()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 LINQ to SQL 中使用 contains()
基础教程推荐
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
