Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}

Like:

public static bool IsAllowed(int userID)
{
    return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}

I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.

like image 657
Marshall Avatar asked Aug 28 '08 18:08

Marshall


2 Answers

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.

like image 165
Jon Sagara Avatar answered Oct 12 '22 23:10

Jon Sagara


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.)

like image 31
Yaakov Ellis Avatar answered Oct 13 '22 00:10

Yaakov Ellis