In .net (c# or vb) expressions, how would you implement SQL\'s handy IN() functionality?
i.e. value in (1, 2, 4, 7)
rather than:
value = 1 or value =
Or using System.Linq
...
(VB.NET)
Enumerable.Contains({1, 2, 4, 7}, value)
or
{1, 2, 4, 7}.Contains(value)
(C#)
Enumerable.Contains(new int[]{1, 2, 4, 7}, value);
or
new int[] {1, 2, 4, 7}.Contains(value);
if((new int[] {1, 2, 4, 7}).Contains(value))
{
// Do some work.
}
As others have pointed out, you could create an In() Extension method (I'll keep it generic so you can use it on any type):
public static bool In<T>(T this obj, IEnumerable<T> col)
{
return col.Contains(obj);
}
So the initial example becomes:
if(value.In(new int[] {1, 2, 4, 7}))
{
// Do some work.
}
using System;
using System.Linq;
static class SqlStyleExtensions
{
public static bool In(this string me, params string[] set)
{
return set.Contains(me);
}
}
Usage:
if (Variable.In("AC", "BC", "EA"))
{
}
I have made an extension method for this that I find quite useful. However, it is not much more than syntactic sugar wrapping the existing IEnumerable.Contains() function.
/// <summary>
/// Returns true if the value is represented in the provided enumeration.
/// </summary>
/// <typeparam name="T">Type of the value</typeparam>
/// <param name="obj">The object to check if the enumeration contains</param>
/// <param name="values">The enumeration that might contain the object</param>
/// <returns>True if the object exists in the enumeration</returns>
public static bool In<T>(this T obj, IEnumerable<T> values) {
return values.Contains(obj);
}
Edit: Someone beat me to it, damnit. I'll keep by post here though since it's a more generic version.
If you will do many lookups on the same dataset it is good from a performance perspective to use HashSet<T>
.
HashSet<int> numbers = new HashSet<int> { 1, 2, 4, 7 };
bool is5inSet = numbers.Contains(5);
Using LINQ
var q = from x in collection
where (new int[] { 1, 2, 4, 7}).Contains(x.value)
select x