在SQL中,您可以使用以下语法:
SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)
在C#中有没有类似的东西?IDE似乎将"in“识别为关键字,但我似乎找不到有关它的任何信息。
那么,有没有可能这样做呢:
int myValue = 1;
if (myValue in (1, 2, 3))
// Do something
而不是
int myValue = 1;
if (myValue == 1 || myValue == 2 || myValue == 3)
// Do something
发布于 2010-07-02 19:13:44
如果您想要编写.In,那么您可以创建一个允许您这样做的扩展。
static class Extensions
{
public static bool In<T>(this T item, params T[] items)
{
if (items == null)
throw new ArgumentNullException("items");
return items.Contains(item);
}
}
class Program
{
static void Main()
{
int myValue = 1;
if (myValue.In(1, 2, 3))
// Do Somthing...
string ds = "Bob";
if (ds.In("andy", "joel", "matt"))
// Do Someting...
}
}
发布于 2010-07-02 18:46:02
我想你要找的就是List.Contains()
。C#具有in
keyword
,而不是operator
,它的用途与您在SQL中所指的完全不同。
有两种方法可以在C#中使用in
关键字。假设您在C#中有一个string[]或List。
string[] names; //assume there are some names;
//find all names that start with "a"
var results = from str in names
where str.StartsWith("a")
select str;
//iterate through all names in results and print
foreach (string name in results)
{
Console.WriteLine(name);
}
参考你的编辑,我会把你的代码放在这里来做你需要的事情。
int myValue = 1;
List<int> checkValues = new List<int> { 1, 2, 3 };
if (checkValues.Contains(myValue))
// Do something
发布于 2013-08-31 03:42:08
您可以这样做:
var x = 99; // searched value
if (new[] {1,2,3,99}.Contains(x))
{
// do something
}
https://stackoverflow.com/questions/3164998
复制相似问题