使用LINQ vb搜索多个关键字

时间:2012-10-02 15:45:39

标签: asp.net database vb.net linq dynamic-queries

我有一些现有的代码需要修改才能搜索多个关键字。 (顺便说一下,我对这一切都是新手)

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中知道这可能有用,但在这种情况下我该如何处理呢?

2 个答案:

答案 0 :(得分: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中看到如何执行lamda表达式。只需将List发送到执行查询的方法,就可以了。

答案 1 :(得分: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