我正在使用LINQ表达式来动态搜索集合中的值,并且我遇到了一个奇怪的问题,这个问题似乎是由搜索String.Format()
操作导致的字符串引起的。< / p>
这是我想要做的简化版本,因为在实践中我实际上并不知道我要搜索的是什么类型的价值,我必须将所有内容视为Object
。
Dim stringToFind As String = "Some Special Value"
' Create a collection of 10 strings, one of which being the string to find '
Dim myStrings As New List(Of Object)
For i As Integer = 0 To 9
If (i = 3) Then
myStrings.Add(String.Format(stringToFind))
Else
myStrings.Add("Boring Plain Old Value")
End If
Next
' Create the predicate for <Function(x) x = stringToFind> '
Dim left = Expression.Parameter(GetType(Object), "x")
Dim right = Expression.Constant(stringToFind)
Dim eq = Expression.Equal(left, right)
Dim predicate = Expression.Lambda(Of Func(Of Object, Boolean))(eq, left).Compile()
' Compare the results '
Dim standardResults = myStrings.Where(Function(x) x = stringToFind)
Dim expressionResults = myStrings.Where(predicate)
' Expected Output:'
' Standard Method: 1 '
' LINQ Expressions: 1 '
Console.WriteLine(String.Format("Standard Method: {0}", standardResults.Count()))
Console.WriteLine(String.Format("LINQ Expressions: {0}", expressionResults.Count()))
Console.ReadLine()
这里发生的是标准方法正确返回1个结果,而LINQ表达式方法返回0.但是,如果在不使用String.Format()(myStrings.Add(stringToFind)
)的情况下将特殊值添加到集合中,则表达式也返回正确的结果。
String.Format()是否会改变字符串的编码,或者会影响如何为字符串值创建常量表达式的任何内容?有没有其他方法可以使用LINQ表达式来比较两个值,这会让我解决这个限制?
答案 0 :(得分:1)
VB.NET等于运算符不进行引用比较。粗略地说,它使用object.Equals
方法(与object.ReferenceEquals
相反)。表达式树使用对象引用相等。
使用string.Format
没有做任何特别的事情。 (没有“特殊”字符串)。