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

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

    I would encapsulate the list of allowed IDs as data not code. Then it's source can be changed easily later on.

    List<int> allowedIDs = ...;
    
    public bool IsAllowed(int userID)
    {
        return allowedIDs.Contains(userID);
    }
    

    If using .NET 3.5, you can use IEnumerable instead of List thanks to extension methods.

    (This function shouldn't be static. See this posting: using too much static bad or good ?.)

    0 讨论(0)
  • 2021-01-04 13:25

    Here's the closest that I can think of:

    using System.Linq;
    public static bool IsAllowed(int userID)
    {
      return new Personnel[]
          { Personnel.JohnDoe, Personnel.JaneDoe }.Contains((Personnel)userID);
    }
    
    0 讨论(0)
  • 2021-01-04 13:28

    Just another syntax idea:

    return new [] { Personnel.JohnDoe, Personnel.JaneDoe }.Contains(userID);
    
    0 讨论(0)
  • 2021-01-04 13:29

    Are permissions user-id based? If so, you may end up with a better solution by going to role based permissions. Or you may end up having to edit that method quite frequently to add additional users to the "allowed users" list.

    For example, enum UserRole { User, Administrator, LordEmperor }

    class User {
        public UserRole Role{get; set;}
        public string Name {get; set;}
        public int UserId {get; set;}
    }
    
    public static bool IsAllowed(User user) {
        return user.Role == UserRole.LordEmperor;
    }
    
    0 讨论(0)
  • 2021-01-04 13:35

    Can you write an iterator for Personnel.

    public static bool IsAllowed(int userID)
    {
        return (Personnel.Contains(userID))
    }
    
    public bool Contains(int userID) : extends Personnel (i think that is how it is written)
    {
        foreach (int id in Personnel)
            if (id == userid)
                return true;
        return false;
    }
    
    0 讨论(0)
  • 2021-01-04 13:36

    How about something like this:

    public static bool IsAllowed(int userID) {
      List<int> IDs = new List<string> { 1,2,3,4,5 };
      return IDs.Contains(userID);
    }
    

    (You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable<>, etc, based on your needs. The main point is that the closest equivalent to the in operator in SQL is the Collection.Contains() function.)

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