2

如何让 Linq 忽略任何为空的参数?那么姓氏,名字等?如果我在所有参数中都有数据,它工作正常......

refinedresult = From x In theresult _
                    Where x.<thelastname>.Value.TestPhoneElement(LastName) And _
                    x.<thefirstname>.Value.TestPhoneElement(FirstName) And _
                    x.<id>.Value.TestPhoneElement(Id) And _
                    x.<number>.Value.TestPhoneElement(Telephone) And _
                    x.<location>.Value.TestPhoneElement(Location) And _
                    x.<building>.Value.TestPhoneElement(building) And _
                    x.<department>.Value.TestPhoneElement(Department) _
                    Select x


Public Function TestPhoneElement(ByVal parent As String, ByVal value2compare As String) As Boolean
'find out if a value is null, if not then compare the passed value to see if it starts with
Dim ret As Boolean = False

If String.IsNullOrEmpty(parent) Then
    Return False
End If
If String.IsNullOrEmpty(value2compare) Then
    Return ret
Else
    ret = parent.ToLower.StartsWith(value2compare.ToLower.Trim)
End If

Return ret
End Function
4

1 回答 1

1

只是为了确保我了解您想要什么:您希望返回 XElements x 的 IEnumerable,其中至少有一个子元素的值与相应的字符串变量匹配。因此,忽略您的意思是您的扩展方法将返回false。所以我推断,如果它不能正常工作,那么一个空参数会导致 TestPhoneElement 返回真(错误地),因此你会得到误报。这意味着,如果参数是空字符串或什么都不是,它总是返回 true,因此您在结果中得到了不应该得到的项目。

我的想法是这样的:

  1. 只有ret = parent.ToLower.StartsWith(value2compare.ToLower.Trim)可能返回true。
  2. value2compare.ToLower.Trim()肯定会导致您指出的问题。
  3. String.IsNullOrEmpty(value2compare)必须返回false。

我相信您传入的第二个参数TestPhoneElement实际上必须是一个至少包含一个空格的字符串。 这样,String.IsNullOrEmpty(value2compare)返回false。然后在最后一行value2compare.ToLower.Trim评估为空字符串,因为您对其进行了修剪,并ret = parent.ToLower.StartsWith(value2compare.ToLower.Trim)评估为,因为每个字符串都以空字符串开头。

因此,当它第一次出现时修剪 value2compare,或者将第二个条件更改为:

If String.IsNullOrEmpty(value2compare.trim()) Then

你应该很好。

编辑:

基于明确情况的解决方案

您希望将一个空字符串传递给扩展方法以产生 True ,对吗?此外,我更新了扩展方法以允许更简洁的代码。但关键是您希望传入任何空白字符串以导致返回 True :

refinedresult = From x In theresult _
            Where x.<thelastname>.MatchesOrIsBlank(LastName) And _
                x.<thefirstname>.MatchesOrIsBlank(FirstName) And _
                x.<id>.MatchesOrIsBlank(Id) And _
                x.<number>.MatchesOrIsBlank(Telephone) And _
                x.<location>.MatchesOrIsBlank(Location) And _
                x.<building>.MatchesOrIsBlank(Building) And _
                x.<department>.MatchesOrIsBlank(Department) _
            Select x

和:

Public Function TestPhoneElement(ByVal xE As XElement, ByVal value2compare As String) As Boolean
    Return xE.Value.ToLower.StartsWith(value2compare.ToLower.Trim)
End Function
于 2010-04-20T19:55:51.743 回答