Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do IN syntax with Linq

I need to do this using linq chaining 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)
like image 718
DotnetDude Avatar asked Jan 04 '11 21:01

DotnetDude


2 Answers

You can use a simple Contains.

var a = Members.Where(x => arr.Contains(x.City));
like image 125
jjnguy Avatar answered Sep 27 '22 18:09

jjnguy


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

Similar to code4life, I use an extension method. The difference, though, is that I use generics so this will work with multiple types.

You can read my blog post to see more information about how to do this, but the main 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 perform your search like this:

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 value type for sure.

like image 38
Gabriel McAdams Avatar answered Sep 27 '22 16:09

Gabriel McAdams