LINQ查询匹配字符串的一部分(小数)

时间:2014-09-26 18:10:20

标签: vb.net linq

我想基于使用LINQ在文本框中输入搜索词的用户动态更新DataGridView。

为了做到这一点,我希望他们输入的内容不必与数据库中的字符串完全匹配,但是例如,如果该公司是“Telexperts'他们输入了Tele' Tele'在文本框中,它将返回所有拥有' Tele'以他们的名义。

这是一些粗略的伪代码:

Dim CompaniesSortedByTextBox = (From c As Company In db.Companies 
                                Where c.CompanyName Contains SortByNameTextBox.Value 
                                Select c).ToList

编辑:很高兴看到这个问题得到了很好的回应。我一直在关注提供的答案,现在我正在使用Contains方法,但我觉得它很慢。我正在根据文本框的更改时间更改数据源,如下所示:

Private Sub FilterDataGridView(sender As System.Object, e As System.EventArgs) 
                                          Handles FilterByCityBox.TextChanged
DataGridViewElements = (From c As Company In db.Companies Select c).ToList 'Reset it.
If (FilterByCityBox.Text <> "") Then
    CompanyInfos = (From c As Company in db.Companies Where c.City.Contains(FilterByCityBox.Text)).ToList
End If
PUCOCompanyRegistry.DataSource = CompanyInfos

它有效,但速度很慢。它要求用户在文本框中的每次击键后等待很长时间(大约半秒钟)。

3 个答案:

答案 0 :(得分:4)

您有几种选择:

  • String.StartsWith可以翻译成SQL:
From c As Company In db.Companies
Where c.CompanyName.StartsWith(SortByNameTextBox.Value)
Select c
  • String.Contains
From c As Company In db.Companies
Where c.CompanyName.Contains(SortByNameTextBox.Value)
Select c
From c As Company In db.Companies
Where SqlMethods.Like(c.CompanyName, "%" + SortByNameTextBox.Value + "%")
Select c
  • 既然你在做VB,我相信它有一个Like运算符:
From c As Company In db.Companies
Where c.CompanyName Like ("*" + SortByNameTextBox.Value + "*")
Select c

以下是一些docs about string mapping

答案 1 :(得分:1)

//should be Filtered not Sorted 
Dim CompaniesSortedByTextBox = (From c As Company In db.Companies 
                                Where c.CompanyName.Contains(SortByNameTextBox.Value) 
                                Select c).ToList

答案 2 :(得分:1)

我还有一个建议,如果你有一个关键字列表并且期望它,CompanyName可以是list中的值之一,你可以这样做。

 Dim lst As New List(Of String) ' assuming c.CompanyName can be = comp1 or comp2 or comp 3
 lst.Add("comp1") : lst.Add("comp3") : lst.Add("comp2")
 Dim CompaniesSortedByTextBox = (From c As Company In db.Companies
                                        Where lst.Contains(c.CompanyName)
                                        Select c).ToList