After reviewing this answer and given the extension method:
public static bool IsIn<T>(this T source, params 开发者_如何学PythonT[] list)
{
if(null == source) throw new ArgumentNullException("source");
return list.Contains(source);
}
What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)
Is it better to write another extension method that would check if a variable is not in a list such as if(x.IsNotIn(1,2,3)) or is it better to just negate the first extension method such as if(!x.IsIn(1,2,3))?
I prefer negation of the positive case method. Why rewrite or clipboard inherit?
It always depends on your use case. In general, you should create extension methods because you find yourself using them, rather than for the sake of the extension method itself. If you find yourself always typing !Item.IsIn(List); You may prefer to write Item.IsNotIn(List); Then again many would suggest !Item.IsIn(List) is more clear (and it's shorter). This really is a personal choice and depends what best fits your problem domain.
Just use: if(!x.IsIn(1,2,3)) { do_stuff(); }
. Contains
just iterates over the array, so there's no terribly good way to optimize it since that's what you'll have to do too.
精彩评论