A SQL-Like IN function for C#

Introduction

This tip presents helper functions similar to the SQL IN clause for use within .NET programs. The intention is to help avoid combining && /|| (And / Or) within complex if statements.

Background

Some considerable time ago, I found myself having to write some fairly complex if-statements combining lots ofAnds with a whole load of Ors. I very quickly found myself wishing that VB6 (I know, I know!) had something similar to the T-SQL construct IN so I could get rid of the "Ors" and simplify the logic.

So I wrote myself some helper functions to do just that. It really wasn't pretty, and fortunately, it has now been condemned to the annals of history (although it is probably still sitting on a backup server somewhere!).

Then recently, I came across a post in Quick Answers where the OP had a very similar problem. Here's a (very much) simplified example of what it looked like...

if (!aBoolTest && (aTest == "++" || aTest == "--" || aTest == "**" || 
                aTest == "^/" || aTest == "/>" || aTest == "/<" || 
                aTest == "</=" || aTest == ">/=" || aTest == "/=") && aDoubleTest == .75)

Wouldn't it be nice if that could be written as something like...

if(!aBoolTest && aTest.IN("++","--",^/","/>","/<","</=",">

Using the Code

Well, in the first attempt in this article, I went completely in the wrong direction. See the comments prior to 13 May 2014 for far better solutions than my original. I guess my mind was still caught up thinking of my old VB6 solution!

However, the solution I was really after is even simpler in the context I'm using it ... to replace all those Ors. You just need an array of the values you are interested in - I've created the array on-the-fly within the if-statement itself - and the thing you're testing for. Then utilize the Contains method of the array. All you have to do is ensure that the array you create is the same type as the object you are testing against.

if (new string[] {"++", "--", "**", "^/", "/>", "/<", "/=", "/="}.Contains(aTest) )
    Debug.Print("Passed");  // Actions when test passes
else
    Debug.Print("Failed");  // Actions when test fails
posted @ 2017-03-16 15:55  KSalomo  阅读(143)  评论(0编辑  收藏  举报