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

后端 未结 8 2212
北恋
北恋 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);
    }
    

提交回复
热议问题