1

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.

andyabel
  • 335
  • 4
  • 15
  • Possible duplicate of [Linq select objects in list where exists IN (A,B,C)](http://stackoverflow.com/questions/14257360/linq-select-objects-in-list-where-exists-in-a-b-c) – Arturo Menchaca May 16 '16 at 16:27
  • @ArturoMenchaca I don't this it is a direct duplicate because the question is asking how to do it without assigning it to a variable. – Matt Rowland May 16 '16 at 16:29

4 Answers4

1

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;
Matt Rowland
  • 4,575
  • 4
  • 25
  • 34
0

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);
AntiTcb
  • 609
  • 4
  • 15
0

...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" ) ) ...
shadow
  • 1,883
  • 1
  • 16
  • 24
0

I figured it out:-

if (new List<string> {"Fred", "Jim", "Harry"}.Contains("Jim"))
andyabel
  • 335
  • 4
  • 15