2010-04-20 74 views
2

如何让LINQ到忽略是空的任何参数?所以姓,名,等等?如果我在所有参数正常工作数据...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 

回答

1

只是为了确保我知道你想什么:你想XElements X的IEnumerable返回的子元素相匹配的值,其中至少一个对应字符串变量。因此,通过忽略你的意思是你的扩展方法将返回。因此,我推断,如果它不做工精细,然后空参数导致真实的(误)由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)评估为true,因为每个字符串开头一个空字符串。

因此,修剪value2compare当它第一次进入时,或改变你第二个有条件的:

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

,你应该是不错的。

编辑:基于澄清情况

你想传递到扩展方法一个空字符串导致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 

+0

我会尝试感谢你回答。 +1这样一个很好的详细的尝试,我会报告,如果它的工作。再次感谢。 – 2010-04-20 20:07:22

+0

好的,我在代码中犯了一个错误。我真的想要“和”每个参数。当我在试图让它工作的时候,我从那里得到了操作系统。所以最终我目前没有得到任何结果。 (我更新了问题)我得到结果的唯一时间是如果所有参数都有。所以是的,它与任何参数中的空字符串有关。 – 2010-04-20 20:20:09

+0

那么,你想* TestPhoneElement *返回真或假在其中* value2compare *参数为空字符串(或没有)的情况下? – 2010-04-21 13:04:02