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

后端 未结 8 2150
北恋
北恋 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:37

    A nice little trick is to sort of reverse the way you usually use .Contains(), like:-

    public static bool IsAllowed(int userID) {
      return new int[] { Personnel.JaneDoe, Personnel.JohnDoe }.Contains(userID);
    }
    

    Where you can put as many entries in the array as you like.

    If the Personnel.x is an enum you'd have some casting issues with this (and with the original code you posted), and in that case it'd be easier to use:-

    public static bool IsAllowed(int userID) {
      return Enum.IsDefined(typeof(Personnel), userID);
    }
    
    0 讨论(0)
  • 2021-01-04 13:42

    How about this?

    public static class Extensions
    {
        public static bool In<T>(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.

    0 讨论(0)
提交回复
热议问题