Something like sql IN query inside .NET framework?

I have this function:

public bool IsValidProduct(int productTypeId) { bool isValid = false; if (productTypeId == 10 || productTypeId == 11 || productTypeId == 12) { isValid = true; } return isValid; } 

but I am wondering if there is an easier way to write it, for example:

  public bool IsValidProduct(int productTypeId) { bool isValid = false; if (productTypeId.In(10,11,12)) { isValid = true; } return isValid; } 

I know that I could write an extension method to handle this, I'm just wondering if there is already something there or there is a better way to write it.

+6
c # language-features
source share
8 answers

No, I don’t believe it that way, but you can write an extension method that allows your code to work exactly as it is written.

 public static bool In<T>(this T source, params T[] args) { return args.Contains(source); } 

The array overhead is a bit. You will probably want to add special cases for a smaller fixed number of parameters.

+5
source share
 new [] {10, 11, 12}.Contains(productTypeId) 
+11
source share

Hmm, you could do this:

 public bool IsValidProduct(int productTypeId) { bool isValid = false; if (new[] {10,11,12}.Contains(productTypeId)) { isValid = true; } return isValid; } 

or if you need the same thing shorter:

 public bool IsValidProduct(int productTypeId) { return (new[] {10,11,12}.Contains(productTypeId)); } 
+3
source share

You could do something line by line:

 new int[] { 10,11,12 }.Contains(productTypeID); 

or further create an extension for int line by line:

 public static bool In(this int i, params int[] ints) { return ints.Contains(i); } 

Using:

 if (productTypeID.In(10,11,12)) { ... } 

I would not say that they are the most effective, but maybe yes.

+2
source share

I don’t think there is anything in this area, so you have to write your own extension method. The closest you can get with linq is something like:

 if(new[] { 10, 11, 12 }.Contains(productTypeId)) { ... } 
+1
source share

You can use the Contains extension method from .NET 3.5. It works with all enumerated types:

 if (new [] { 10, 11, 12 }.Contains(productTypeId)) { ... } 
0
source share

var validIds = new [] {10, 11, 12};
validIds.Contains (ProductID);

0
source share

This will work if the number you need is in the range and not in the "IN" functionality, but you may find it useful.

 if (Enumerable.Range(10, 3).Contains(productTypeId)) 
0
source share

All Articles