In SQL I can write:-
if (product_type in ('abc','def','ghi')) ...
How can I write a similarly concise 'if' statement in C#? I don't want to have to pre-create a named string list variable. Thanks.
In SQL I can write:-
if (product_type in ('abc','def','ghi')) ...
How can I write a similarly concise 'if' statement in C#? I don't want to have to pre-create a named string list variable. Thanks.
To simplify this you would use this line.
if (new[] {"abc", "def", "ghi"}.Contains(product_type)) //...
Don't forget to add the declaration
using System.Linq;
You can create an anonymous collection inline and perform the same method calls on it as if it were named.
var product_type = "abc";
// Array
var result = new [] {"abc", "def", "ghi"}.Contains(product_type); // result == true.
// List
var listResult = new List<string> {"abc", "def", "ghi"}.Contains(product_type);
...or you can create an extension to have the In for everything
public static bool In<T>(this T obj, IEqualityComparer<T> comparer, params T[] list)
{
if (comparer == null)
return list.Contains(obj);
else
return list.Contains(obj, comparer);
}
public static bool In<T>(this T obj, params T[] list)
{
return In(obj, null, list);
}
so you could write something like:
if ( product_type.In( "abc", "def", "ghi" ) ) ...
I figured it out:-
if (new List<string> {"Fred", "Jim", "Harry"}.Contains("Jim"))