0

我有一些现有代码需要修改以搜索多个关键字。(顺便说一句,我对这一切都很陌生)

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

我将如何改变这一点,所以如果我输入标准“猫毛”,它将进行 OR 搜索。所以...t.TopicTitle.Contains("cat") OR t.TopicTitle.Contains("hair") ...。当然,它需要是动态的。

我试过这个,但无法让它工作。

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

想法是拆分空格并继续附加到 where 子句。我知道在 SQL 中这可能有效,但在这种情况下我将如何进行呢?

4

2 回答 2

1

您可以使用.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:

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

这是获取strings查询词列表,并检查其中是否TopicTitle包含其中的任何一个。

抱歉,那是在 C# 中,但你可以在.Where. 只需向List执行查询的方法发送一个,就可以了。

于 2012-10-02T15:50:30.220 回答
0

假设 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
于 2012-10-02T18:19:06.517 回答