Reputation: 11807
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)
Upvotes: 8
Views: 5629
Reputation: 58251
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.
Upvotes: 5
Reputation: 15794
Static extensions work well with your LINQ needs:
// 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 original code can be changed like this:
// 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);
Upvotes: 0
Reputation: 138864
You can use a simple Contains
.
var a = Members.Where(x => arr.Contains(x.City));
Upvotes: 9