Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Building a C# equivalent of the MS SQL construct IN?

Often in MS SQL, I use IN, to check if a value is in a list of items, e.g.

WHERE @x IN (1,2,3,5,8,13)

I’ve got as close as I can by defining the following in a library function, thus:

public static bool IIN(object oValue, params object[] oValues)
{
    int i;

    for (i = 0; i <= oValues.GetUpperBound(0); i++)
    {
        if ((oValue.ToString()) == (oValues[i].ToString())) return true;
    }
    return false;
}

In this way I can call it thus:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

bool bItemFound = IIN(x,1,2,3,5,8,13);

However, because it is in a library, I end up having to reference the library, thus:

bool bItemFound = MyProject.Common.Helpers.CoreHelper.IIN(x,1,2,3,5,8,13);

This really clutters the code. I’ve tried declaring a Lambda function thus at the top of my calling class:

Func<object, params object[], bool> IIN = (a, b) => { return MyProject.Common.Helpers.CoreHelper.IIN(a, b); };

But Lambda declarations seem to not like having param arrays. I can make the b parameter an object array, thus:

public static bool IIN2(object oValue, object[] oValues)
{
    int i;

    for (i = 0; i <= oValues.GetUpperBound(0); i++)
        if ((oValue.ToString()) == (oValues[i].ToString())) return true;

    return false;
}

And my Lambda declaration is:

Func <object, object[], bool> IIN = (a, b) => { return CoreHelper.IIN2(a, b); };

But then I have to declare an inline throwaway object[] in my calling code:

bool bItemFound = IIN(x, new object[] { 1,2,3,5,8,13 });

Is there a neater way of doing this, being as clean and as readable as the SQL equivalent?

>Solution :

This really clutters the code.

If the only goal is to remove this part:

MyProject.Common.Helpers.CoreHelper.

Then a using static directive can do that. For example, if you include this directive at the top of the file:

using static MyProject.Common.Helpers.CoreHelper;

Then you can call the method directly:

bool bItemFound = IIN(x,1,2,3,5,8,13);

I haven’t tested this, but you may even be able to combine it with the global using directive in C# 10:

global using static MyProject.Common.Helpers.CoreHelper;

Which should allow the use of that method throughout the files included in the project.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading