Mark Mintoff My superpower is common sense

27Mar/124

C# Equivalent for SQL IN

One of the things that irks the most when reading code is cumbersome and long-winded IF statements to the tune of:

Naturally, this could be easily typed out as:

But I am not entirely comfortable with this. Certainly it is infinitely better than trying to cram all those possibilities for a into one line, but there must be a more readable syntax. SQL has the answer with the IN statement. For example:

I wanted to emulate this syntax in C#, so I wrote the following extension method which effectively mimics the SQL IN syntax:

or alternatively as Andreas suggested in the comments below:

What this does conceptually, is incredibly simple. You pass to it a generic List or an array and it simply loops on that array searching for a match returning true or false, depending on whether a match has been found. Conceptually, this is akin to the SQL IN syntax.

What this means, is that we can now type the above cumbersome IF statement as:

Which I feel, is a noticeable improvement in the readability of a long-winded collection of OR conditions in a single IF statement.

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
Tagged as: , , Leave a comment
Comments (4) Trackbacks (0)
  1. You can also work the other way round and use the existing ‘Contains’ extension method:

    if (new string[]{ “abc”, “def”, “ghi”, “jkl”, “mno” }.Contains(a)) { …

    And if you want to keep the ‘In’ extension method, you can simply change it to a one-liner:

    public static bool In<T>(this T args, T[] prms)
    {
    return prms.Contains(args);
    }

    • Fixed your code :)
      Next time type it up with &lt; and &gt; ;)

      I don’t particularly like reversing it. In fact this exercise was an exercise in creating an equivalent to the SQL Syntax. Using In feels a lot more natural.

      Contains in the extension method is an interesting alternative to a foreach loop. Here’s another:

      return prms.Where(x => x.Equals(args)).Count() > 0;

  2. Yea cheers for that…I realized I had to encode the brackets afterwards :p
    Btw though, you didn’t need to prepend my [] with ‘string’ because the compiler infers that for you.

    As regards the example in your comment, I don’t think using the Where like that would be an optimal solution because it will iterate over all of your elements in the collection, whereas in the for-each you used in your post and ‘Contains’, the method will terminate once the predicate is met.

    • Live and learn! I had no idea that the compiler would infer that, cheers.
      I edited it into my post.

      You’re right about the Where example as well. Didn’t think it through very well :)

      I actually used your Contains advice in my project source code. I can’t quite resist a one-liner like that :)


Cancel reply

No trackbacks yet.