Often in SQL Server, I use IN
to check if a value is in a list of items, for example:
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;
}
I can call that function like thus:
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?
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.