【问题标题】:VB.net LINQ filter on multiple columns多列上的 VB.net LINQ 过滤器
【发布时间】:2013-03-16 02:07:54
【问题描述】:

您好,请您告诉我在 LINQ 中实现多列过滤的最佳方法

表:

CREATE TABLE [dbo].[user] (
[id] [int] IDENTITY(1,1) NOT NULL,
[firstName] [nvarchar](50) NULL,
[surname] [nvarchar](50) NULL,
[fullAddress] [nvarchar](1050) NULL

我通常会为此使用 SQL

Dim firstname as string = 'bob'
Dim surname as String = 'holdness'
Dim address as String = 'blockbuster street'
Dim Stmquery as string = 'Select * from users '
if not String.isnullorEmpty(firstname) or not String.isnullorEmpty(surname) or not String.isnullorEmpty(address) then 
Stmquery = Stmquery & "where"
end if
if not String.isnullorEmpty(firstname) then
Stmquery = Stmquery & " firstname = " & firstname
end if
    if not String.isnullorEmpty(surname) then
Stmquery = Stmquery & " surname = " & surname
end if
    if not String.isnullorEmpty(address) then
Stmquery = Stmquery & " address = " & address
end if

所以基本上如果字符串为空,它将显示该列的所有记录

谁能告诉我如何在 LINQ 中做到这一点

谢谢保罗

【问题讨论】:

    标签: sql vb.net linq search filter


    【解决方案1】:

    我假设您已经准备好 LINQ to SQL DBContext,并映射了 Users 表。

    您可以轻松扩展您的查询,因为在您调用 ToList()ToArray()First()Last() 等之前,它不会针对数据库执行。

    Dim query = dbContext.Users;
    
    If Not String.IsNullOrEmpty(firstname) Then
        query = query.Where(Function(u) u.FirstName = firstname)
    End If
    
    If Not String.IsNullOrEmpty(surname) Then
        query = query.Where(Function(u) u.Surname = surname)
    End If
    
    If Not String.IsNullOrEmpty(address) Then
        query = query.Where(Function(u) u.Address = address)
    End If
    
    ' query execution is here, after next line '
    Dim results = query.ToList()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多