Combining multiple conditional expressions in C#

前端 未结 9 1034
一个人的身影
一个人的身影 2021-01-30 11:24

In C#, instead of doing if(index == 7 || index == 8), is there a way to combine them? I\'m thinking of something like if(index == (7, 8)).

相关标签:
9条回答
  • 2021-01-30 12:03
    switch (GetExpensiveValue())
    {
    case 7: case 8:
       // do work
       break;
    }
    

    This obviously takes more code, but it may save you from evaluating a function a bunch of times.

    0 讨论(0)
  • 2021-01-30 12:03
    if ((new int[]{7,8}).Contains(index))
    
    0 讨论(0)
  • 2021-01-30 12:04

    Do u need something like that

            int x = 5; 
    
            if((new int[]{5,6}).Contains(x)) 
            {
                Console.WriteLine("true");
    
    
            }
            Console.ReadLine();
    
    0 讨论(0)
  • 2021-01-30 12:06

    Write your own extension methods so you can write

    if (index.Between(7, 8)) {...}
    

    where Between is defined as:

        public static bool Between (this int a, int x, int y)
        {
            return a >= x && a <= y;
        }
    
    0 讨论(0)
  • 2021-01-30 12:07

    You could put the values that you need to compare into an inline array and use a Contains extension method. See this article for starters.

    Several snippets demonstrating the concept:

    int index = 1;
    Console.WriteLine("Example 1: ", new int[] { 1, 2, 4 }.Contains(index));
    
    index = 2;
    Console.WriteLine("Example 2: ", new int[] { 0, 5, 3, 4, 236 }.Contains(index));
    

    Output:

    Example 1: True
    Example 2: False
    
    0 讨论(0)
  • 2021-01-30 12:08

    You can accomplish this with an extension method.

    public static bool In<T>(this T obj, params T[] collection) {
       return collection.Contains(obj);
    }
    

    Then...

    if(index.In(7,8))
    {
        ...
    }
    
    0 讨论(0)
提交回复
热议问题