有C#IN运算符吗?

问题描述 投票:78回答:13

在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
c# sql operators in-operator
13个回答
108
投票

如果你想写。那么你可以创建一个允许你这样做的扩展。

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...
    }
}

1
投票

运算符中没有查找集合中的值,而是集合的方法,称为Contains

最具扩展性的解决方案是使用HashSet作为集合。检查HashSet中的值是否接近于O(1)操作,与在List中进行O(n)操作相比。这意味着你可以在HashSet中包含很多值并且它仍然很快,而在List中查找值会越慢,你拥有的值越多。

例:

var set = new HashSet<int>();
set.Add(1);
set.Add(2);
set.Add(3);

var result = items.Select(i => set.Contains(i.value));

1
投票

对于0到9之间的数字:

"123".Contains(myValue)

对于任何其他东西:

"|1|2|3|".Contains("|" + myValue + "|")

1
投票

常见的,LINQ方式更强大:

var list = new List<string> { "Tomato", "Orange", "Mango"};
var query = from i in my_table
            from v in list
            where i.Name.StartsWith(v)
            select i;

0
投票

C#中的in关键字用于foreach语句和LINQ查询表达式。在C#本身中没有与SQL的in运算符等效的功能,但LINQ提供与Contains()类似的功能。

var list = {1, 2, 3}
var filtered = (
    from item in items
    where list.Contains(item)
    select item).ToArray().

81
投票

List.Contains()我认为你在寻找什么。 C#有in keyword而不是operator,它的用途完全不同于你在SQL中提到的用途。

有两种方法可以在C#中使用in关键字。假设您在C#中有一个字符串[]或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 

22
投票

你可以这样做:

var x = 99; // searched value

if (new[] {1,2,3,99}.Contains(x))
{
   // do something
}

7
投票

您通常使用集合的Contains方法。

myCollection.Where(p => Enumerable.Range(1,3).Contains(p));

我希望它有所帮助。


6
投票

C#中没有“in”运算符,“in”关键字仅用于“foreach(... in ...)”或“from ... in ...”。

LINQ等效的SQL查询将是:

List<int> list = new List<int> { 1, 2, 3 };
var query = from row in my_table
            where list.Contains(row.value1)
            select row;

4
投票

重复:LINQ to SQL in and not in

select * from table where fieldname in ('val1', 'val2') 

要么

select * from table where fieldname not in (1, 2) 

LINQ to SQL中的IN和NOT IN查询的等价物如下所示:

List<string> validValues = new List<string>() { "val1", "val2"}; 
var qry = from item in dataContext.TableName 
          where validValues.Contains(item.FieldName) 
          select item; 

还有这个:

List<int> validValues = new List<int>() { 1, 2}; 
var qry = from item in dataContext.TableName 
          where !validValues.Contains(item.FieldName) 
          select item; 

4
投票

我同意实现In运算符的最佳方法是使用Extension方法。我做的有点不同:

public static bool In(this string str, string CommaDelimintedStringSet)
{
    string[] Values = CommaDelimintedStringSet.Split(new char[] { ',' });
    foreach (string V in Values)
    {
       if (str == V)
         return true;
    }
    return false;
}

区别在于您不必在每个值周围加上引号,只需要整个逗号分隔值集,这样更容易输入:

bool result = MyString.In("Val1,Val2,Val3");

2
投票

你可以写一个扩展名。我在一段时间前写过,因为代码就像

if(someObject.stringPropertyX.Equals("abc") || someObject.stringPropertyX.Equals("def") || ....){
    //do something
    ...
}else{
   //do something other...
   ....
}

更具可读性,扩展名为a.t.一个人能够写

if(someObject.stringPropertyX.In("abc", "def",...,"xyz"){
   //do something
   ...
}else{
  //do something other...
  ....
}

这是code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Some.Namespace.Extenders
{
    public static class StringExtender
    {
        /// <summary>
        /// Evaluates whether the String is contained in AT LEAST one of the passed values (i.e. similar to the "in" SQL clause)
        /// </summary>
        /// <param name="thisString"></param>
        /// <param name="values">list of strings used for comparison</param>
        /// <returns><c>true</c> if the string is contained in AT LEAST one of the passed values</returns>
        public static bool In(this String thisString, params string[] values)
        {
            foreach (string val in values)
            {
                if (thisString.Equals(val, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }

            return false; //no occurence found
        }
    }
}

这是我当时特定的需求,但您可以调整和修改它以匹配更多不同类型。


2
投票

对于更新的问题,您还可以使用switch语句。

switch (myvalue)
{
   case 1:
   case 2:
   case 3: 
      // your code goes here
  break;
}
© www.soinside.com 2019 - 2024. All rights reserved.