There is in operator in SQL
SELECT * FROM MyTable WHERE id 开发者_JAVA技巧IN (1, 2, 3, 4, 5)
Is there similar sintax in C#, I mean
if(variable in (1, 2, 3, 4, 5)){
}
You can have
int[] data = {1, 2, 3, 4, 5};
if(data.Contains(variable))
{
}
There isn't a good one but you can write it yourself as an extension method:
public static class Extensions
{
public static bool In<T>(this T value, params T[] items)
{
return items.Contains(value);
}
}
if (v.In(1,2,3,5)) { /* do stuff */ }
I haven't tested it, but it should be good.
UPDATE: As suggested by OP, I've corrected a few typos.
If you're using .NET 3.5 or newer then you can use Contains
:
if (new[] { 1, 2, 3, 4, 5 }.Contains(variable))
{
// do something
}
With Enumerable.Contains
new int[]{1,2,3,4,5}.Contains(variable)
It is easy enough to put together an extension.
public static bool In<T>(this T value, params T[] items) where T : IEquatable<T>
{
foreach (var item in items)
{
if (value.Equals(item))
{
return true;
}
}
return false;
}
精彩评论