Shorthand conditional in C# similar to SQL 'in' keyword

后端 未结 8 2158
北恋
北恋 2021-01-04 12:44

In C# is there a shorthand way to write this:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneD         


        
8条回答
  •  星月不相逢
    2021-01-04 13:42

    How about this?

    public static class Extensions
    {
        public static bool In(this T testValue, params T[] values)
        {
            return values.Contains(testValue);
        }
    }
    

    Usage:

    Personnel userId = Personnel.JohnDoe;
    
    if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
    {
        // Do something
    }
    

    I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.

提交回复
热议问题