Is there a C# IN operator?

后端 未结 14 1840
说谎
说谎 2020-12-08 03:51

In SQL, you can use the following syntax:

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

Is there an equivalent in C#? The IDE seems to

14条回答
  •  失恋的感觉
    2020-12-08 04:27

    You can write an extension. I wrote one time ago, for making code like

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

    more readable with an extention s.t. one was able to write

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

    Here's the code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace Some.Namespace.Extenders
    {
        public static class StringExtender
        {
            /// 
            /// Evaluates whether the String is contained in AT LEAST one of the passed values (i.e. similar to the "in" SQL clause)
            /// 
            /// 
            /// list of strings used for comparison
            /// true if the string is contained in AT LEAST one of the passed values
            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
            }
        }
    }
    

    This is the one specific to my needs at that time, but you may adapt and modify it to match more different types.

提交回复
热议问题