Czy jest operator C# w?

W SQL możesz użyć następującej składni:

SELECT *
FROM MY_TABLE
WHERE VALUE_1 IN (1, 2, 3)

Czy istnieje odpowiednik w C#? IDE zdaje się rozpoznawać "in" jako słowo kluczowe, ale nie wydaje mi się, abym mógł znaleźć na jego temat żadnych informacji.

Więc, czy można zrobić coś takiego jak:

int myValue = 1;
if (myValue in (1, 2, 3))
    // Do something

Zamiast

int myValue = 1;
if (myValue == 1 || myValue == 2 || myValue == 3)
    // Do something
Author: abatishchev, 2010-07-02

13 answers

Jeśli chcesz napisać .In, możesz utworzyć rozszerzenie, które pozwoli ci to zrobić.

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...
    }
}
 94
Author: Andy Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:13:43

List.Contains() myślę, że tego szukasz. C # ma in keyword a nie operator, który służy zupełnie innemu celowi niż to, o czym mówisz w SQL.

Są dwa sposoby użycia słowa kluczowego in W C#. Załóżmy, że masz ciąg znaków [] lub listę w C#.

        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);
        }

Odnosząc się do Twojej edycji, umieściłbym Twój kod w ten sposób, aby zrobić to, czego potrzebujesz.

        int myValue = 1;
        List<int> checkValues = new List<int> { 1, 2, 3 };

        if (checkValues.Contains(myValue))
            // Do something 
 74
Author: this. __curious_geek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:06:25

Możesz to zrobić:

var x = 99; // searched value

if (new[] {1,2,3,99}.Contains(x))
{
   // do something
}
 18
Author: JwJosefy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-30 19:42:08

Nie ma operatora" in "W C#, słowo kluczowe" in "jest używane tylko z" foreach (... do środka ...) "lub" od ... do środka ...".

Odpowiednikiem LINQ twojego zapytania SQL będzie:

List<int> list = new List<int> { 1, 2, 3 };
var query = from row in my_table
            where list.Contains(row.value1)
            select row;
 6
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 10:48:20

Zazwyczaj używa się metody Contains zbioru.

myCollection.Where(p => Enumerable.Range(1,3).Contains(p));
Mam nadzieję, że to pomoże.
 6
Author: luckyluke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-28 11:25:17

Duplikat: LINQ to SQL in and not in

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

Lub

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

Odpowiednikiem zapytań IN I NOT in w LINQ do SQL byłoby coś takiego:

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

I to:

List<int> validValues = new List<int>() { 1, 2}; 
var qry = from item in dataContext.TableName 
          where !validValues.Contains(item.FieldName) 
          select item; 
 4
Author: Pranay Rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:32:17

Zgadzam się, że najlepszym sposobem implementacji operatora In jest metoda rozszerzenia. Zrobiłem to trochę inaczej:

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

Różnica polega na tym, że nie musisz umieszczać cudzysłowów wokół każdej wartości, tylko cały zestaw wartości rozdzielanych przecinkami, co jest łatwiejsze do wpisania:

bool result = MyString.In("Val1,Val2,Val3");
 4
Author: Chuck Bevitt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-24 20:17:12

Możesz napisać rozszerzenie. Pisałem kiedyś, za zrobienie kodu jak

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

Bardziej czytelny z rozszerzeniem s. T. jeden był w stanie napisać

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

Oto kod :

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
        }
    }
}
To jest ten specyficzny dla moich potrzeb w tamtym czasie, ale możesz go dostosować i zmodyfikować, aby pasował do większej liczby różnych typów.
 2
Author: Juri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:10:38

Dla Ciebie zaktualizowane pytanie

Użyj przełącznika

switch (myvalue)
{
   case 1:
   case 2:
   case 3: 
      // your code gose here
  break;
}
 1
Author: Pranay Rana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:05:23

Nie ma operatora in, który szuka wartości w zbiorze, zamiast tego jest to metoda zbioru o nazwie Contains.

Najbardziej skalowalnym rozwiązaniem jest użycie HashSet jako zbioru. Sprawdzanie wartości w HashSet jest bliskie operacji O(1), w porównaniu do wykonywania jej w List, Gdzie jest operacją O(n). Oznacza to, że możesz spakować wiele wartości w HashSet i nadal jest to szybkie, podczas gdy szukanie wartości w List staje się wolniejsze im więcej wartości mam.

Przykład:

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

var result = items.Select(i => set.Contains(i.value));
 1
Author: Guffa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:12:38

Dla cyfr od 0 do 9:

"123".Contains(myValue)

Dla innych rzeczy:

"|1|2|3|".Contains("|" + myValue + "|")
 1
Author: user3354025,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-26 03:23:02

Słowo kluczowe in W C# dotyczy instrukcji foreach oraz wyrażeń zapytań LINQ. Nie ma funkcjonalności równoważnej operatorowi in SQL w C# per se, ale LINQ oferuje podobną funkcjonalność z Contains().

var list = {1, 2, 3}
var filtered = (
    from item in items
    where list.Contains(item)
    select item).ToArray().
 0
Author: P Daddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-02 11:03:45

Common, LINQ way more powerful:

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
Author: bjolfr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-06 18:18:37