开发者

Linq contains confusion

I have noticed something odd with linq and the Contains method. It seems to get confused on which Contains method to call.

if (myString.Contains(strVar, StringComparison.OrdinalIgnoreCase))
{
  // Code here                  
}

The above code doesn't compile with the f开发者_如何学JAVAollowing error:

The type arguments for method 'System.Linq.Enumerable.Contains(System.Collections.Generic.IEnumerable, TSource, System.Collections.Generic.IEqualityComparer)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

If I remove the using linq statement it is happy with the contains (but brakes all the linq code).

What is the correct syntax to tell the compiler I want to use the String.Contains method and not Linqs?

Cheers


This is because there's no String.Contains(string, StringComparison) method defined in the BCL and the compiler tries to use an extension method. There's only String.Contains(string) method defined.


What is the correct syntax to tell the compiler I want to use the String.Contains method and not Linqs?

There is no overload of String.Contains that accepts a StringComparision. You might want to use String.IndexOf(string, StringComparison):

// s is string
if(s.IndexOf(strVar, StringComparison.OrdinalIgnoreCase) >= 0) {
    // code here
}


It could be because the string.Contains method takes only one parameter (a string; there is no overload of string.Contains that takes a StringComparison value), while the Enumarable.Contains extension method takes two. However, the parameters that you supply do not fit the expected input types, so the compiler gets confused.


As Darin Dimitrov said, String.Contains(string, StringComparison) does not exist as a method for the String type.

System.Linq.Enumerable however does contain such a signature. And a string is also an IEnumerable<char>, that's why the compiler gets confused. You would actually be able to leverage Linq and compile if you replaced the StringCompar-ison with an ICompar-er of Char:

if (myString.Contains(strVar, Comparer<Char>.Default))
{
    // Code here                  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜