开发者

collection/string .Contains vs collection/string.IndexOf

开发者 https://www.devze.com 2022-12-30 01:16 出处:网络
Is there a reason to use .Contains on a string/list instead of .IndexOf? Most code that I would write using .Contains would shortly after need the index开发者_JAVA百科 of the item and therefore would

Is there a reason to use .Contains on a string/list instead of .IndexOf? Most code that I would write using .Contains would shortly after need the index开发者_JAVA百科 of the item and therefore would have to do both statements. But why not both in one?

if ((index = blah.IndexOf(something) >= 0)
    // i know that Contains is true and i also have the index


You are right that IndexOf is a more general operation than Contains. However, Contains is still very useful because it represents the operation explicitly.

if(blah.IndexOf(something) >=0)
{
}

isn't as obvious an operation as

if(blah.Contains(something))
{
}

so if you need the index, then you should use the IndexOf operation, if you only need to know if the string contains the substring then use Contains.

Use the tool for the job it was created for.


One reason you'd want to use Contains is that it has an overload which lets you specify an IEqualityComparer<String> (in case you want the comparison to be case-insensitive or something). IndexOf has no such overload.


they are different functions intended for different purposes, but you can use IndexOf to mimic Contains.

The reason to use Contains? In Linq, especially when translated into sql, gets turned into a relatively simple sql statement, IndexOf is more complicated to translate

0

精彩评论

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

关注公众号