【问题标题】:vb.net linq where clause for mutiple search filter - same query but different where clause用于多个搜索过滤器的 vb.net linq where 子句 - 相同的查询但不同的 where 子句
【发布时间】:2016-01-29 13:37:57
【问题描述】:

我知道这个问题是用 c# 回答的,但是当我尝试将它从 c# 在线转换为 vb.net 时,我遇到了运行错误。

免责声明这是不是我的代码

   string personName = txtPersonName.Text;
   int personAge = Convert.ToInt32(txtAge.Text);
   var opportunites =  from p in this.DataContext.Persons
                        select new
                        {
                            p.PersonID,
                            p.Name,
                            p.Age,
                            p.Gender
                        };

    if (personsID != 0)
        opportunites = opportunites.Where(p => p.PersonID == personID);

    if (personName != string.Empty)
        opportunites = opportunites.Where(p => p.Name.StartsWith(personName));

    if (personAge != 0)
        opportunites = opportunites.Where(p => p.Age == personAge);

有人可以帮我转换这段代码吗?我认为它是 c#,但我无法将它正确转换为 vb.net 我试过 telerik 但没有运气。

我无法在我的 if 语句中调用/使用 linq select new {} 中的“p”。

【问题讨论】:

    标签: c# vb.net linq


    【解决方案1】:

    您似乎在两个方面遇到了问题:匿名类型和 lambda - 下面的转换应该可以澄清这些问题: 选项推断开启

    Dim personName As String = txtPersonName.Text
    Dim personAge As Integer = Convert.ToInt32(txtAge.Text)
    Dim opportunites = From p In Me.DataContext.Persons
        Select New With {
            Key p.PersonID,
            Key p.Name,
            Key p.Age,
            Key p.Gender
        }
    
    If personsID <> 0 Then
        opportunites = opportunites.Where(Function(p) p.PersonID = personID)
    End If
    
    If personName <> String.Empty Then
        opportunites = opportunites.Where(Function(p) p.Name.StartsWith(personName))
    End If
    
    If personAge <> 0 Then
        opportunites = opportunites.Where(Function(p) p.Age = personAge)
    End If
    

    【讨论】:

    • 哥们你太棒了!谢谢。也许以后我会研究它为什么有效!
    【解决方案2】:

    只需选择您想要的值。 vb 中隐含匿名类型

    https://msdn.microsoft.com/en-us/library/bb384767.aspx

    Dim personName As String = "Joe"
    Dim personAge As Integer = Convert.ToInt32(5)
    Dim opportunites = From p IN AspNetUsers
                       Select p.Id,
                              p.FirstName,
                              p.LastName
    
    If (personAge <> 0)
        opportunites = From o In opportunites Where o.Id >= 10
    End If
    

    【讨论】:

    • if 语句块怎么样 我如何调用'p.PersonID' 就像在示例中一样?
    • 我将第一个 if 从 personId 更改为 personAge 因为您没有在示例中声明 personId。我遇到了编译器错误
    猜你喜欢
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多