How to make IN syntax with Linq

I need to do this using linq binding syntax. I have:

string[] arr = new string[] {"Chicago", "NewYork"}; var a = Members.Where(x => x.City == <here I want to get all members in chicago or newyork) 
+6
c # linq linq-to-objects
source share
3 answers

You can use simple Contains .

 var a = Members.Where(x => arr.Contains(x.City)); 
+7
source share

I know this is old, but I thought it would help new readers of this post.

Like code4life , I use an extension method. The difference, however, is that I use generics, so this will work with several types.

You can read my post to find out more about how to do this, but the basic idea is this:

By adding this extension method to your code:

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

you can search as follows:

 var a = Members.Where(x => x.City.IsIn("Chicago", "NewYork"); 

It works on any type (as long as you create a good equals method). Any type of value for sure.

+3
source share

Static extensions work well with your LINQ requirements:

 // add this class to your project... public static class StringExtensions { public static bool IsIn(this string target, params string[] testValues) { return testValues.Contains(target); } } 

And now your source code can be changed as follows:

 // quick and dirty code: var a = Members.Where(x => x.City.IsIn("Chicago", "NewYork"); // less quick and dirty code: string[] arr = new string[] {"Chicago", "NewYork"}; var a = Members.Where(x => x.City.IsIn(arr); 
0
source share

All Articles