[英]Search for multiple keywords using LINQ vb
I have some existing code that I need to modify to search more than one keyword. 我有一些现有代码需要修改以搜索多个关键字。 (I am new to all this by the way)
(顺便说一句,我是新手)
Dim topics As IQueryable(Of Global.Platform.Core.Data.Topic) = _
From t In _db.Topics
Where t.IsActive = True And t.TopicTitle.Contains(criteria) And t.ForumID = 0 And Not t.TopicTitle.Contains("default") And t.Member.IsActive = True And t.IsActive = True
Order By t.DateCreated Descending
Select t
Take (take_x)
Return topics
How would i go about changing this so if I entered criteria "cat hair" it would do an OR search. 我将如何进行更改,因此,如果我输入标准“猫毛”,它将进行“或”搜索。 so
...t.TopicTitle.Contains("cat") OR t.TopicTitle.Contains("hair") ...
. 所以
...t.TopicTitle.Contains("cat") OR t.TopicTitle.Contains("hair") ...
Of course it would need to be dynamic. 当然,它必须是动态的。
I tried this but could not get it to work. 我试过了,但无法正常工作。
Dim criteriaArr As Array = criteria.Split(" ")
Dim new_criteria As String = " t.TopicTitle.Contains(" + criteriaArr(0) + ")"
If criteriaArr.Length > 1 Then
For Each item As String In criteriaArr
new_criteria += " Or t.TopicTitle.Contains(" + item + ")"
Next
End If
The idea was to split the spaces and keep appending to the where clause. 想法是分割空格并继续追加到where子句。 I know in SQL this might have worked, but how would I go about in this scenario?
我知道在SQL中这可能有效,但是在这种情况下我将如何处理?
You can use a combination of .Any
and .Contains
: 您可以使用的组合
.Any
和.Contains
:
var strings = new List<string> { "cat", "dog", "bill" };
using (var context = new MyEntities())
{
var matches = context.MyObject.Where(x => strings.Any(s => x.TopicTitle.Contains(s)));
}
VB: VB:
Dim strings = {"cat", "dog", "bill"}
Using context = New MyEntities()
Dim matches = context.MyObject.Where(Function(x) strings.Any(Function(s) x.TopicTitle.Contains(s)))
End Using
This is taking the strings
list of query words, and checking to see if there are any of them that the TopicTitle
contains. 这将获取查询词的
strings
列表,并检查TopicTitle
包含其中的任何一个。
Sorry, that's in C#, but you can see how to do the lamda expression in the .Where
. 抱歉,在C#中,但是您可以在
.Where
看到如何执行lamda表达式。 Just send in a List
to your method that does the query, and you're good to go. 只需将
List
发送到执行查询的方法中,就可以了。
Assuming TopicTitle and the criteria are space delimited strings I would intersect the two collections and check if there were any matches. 假设TopicTitle和条件是用空格分隔的字符串,那么我将两个集合相交,并检查是否存在任何匹配项。
Dim topics As IQueryable(Of Global.Platform.Core.Data.Topic) = _
From t In _db.Topics
Where t.IsActive = True And t.TopicTitle.Intersect(criteria).Any()
And t.ForumID = 0 And Not t.TopicTitle.Contains("default")
And t.Member.IsActive = True And t.IsActive = True
Order By t.DateCreated Descending
Select t
Take (take_x)
Return topics
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.