Home > C# > Linq “in” clause

Linq “in” clause

So… today I needed to do a simple query like

SELECT * FROM Activities a Where a.Community in ('Community 1', 'Community 2', 'Community 3')

…with Linq.

In the objects world this is managed using the Contains method of IList. The perfect Linq for the previous query is:

var communities = new []{ "Community 1", "Community 2", "Community 3" };
var result = activities.Where(x => communities.Contains(x.Community));

The problem with this is no all Linq providers understands it. And SPLinq (Linq for SharePoint) is one of those who doesn’t.

The other way to handle this kinds of queries is, in SQL:

SELECT * FROM Activities a Where a.Community = 'Community 1' or a.Community = 'Community 2' or a.Community =  'Community 3'

But how to create the Linq query dynamically? Well… All these months working with Magiq gived me the ability of compile Expression trees in my head 🙂

This is the code needed:

private static IQueryable<T> Where<T>(this IQueryable<T> self, Expression<Func<T,object>> property, IEnumerable<string> @in)
{
	var propertyName = ((MemberExpression)property.Body).Member.Name;

	Expression expression = null;

	var x = Expression.Parameter(typeof (ActivityItem), "x");
	foreach (var community in @in)
	{
		var propertyExpression = Expression.Property(x, propertyName);
		var equal = Expression.Equal(propertyExpression, Expression.Constant(community));
		expression = expression == null ? equal : Expression.Or(expression, equal);
	}

	if (expression == null)
		return list;

	var lamda = Expression.Lambda<Func<T, bool>>(expression, x);
	return self.Where(lamda);
}

var communities = new []{ "Community 1", "Community 2", "Community 3" };
var result = activities.Where(x => x.Community, @in: communities);

Linq rules!!

Advertisements
Categories: C# Tags: , , , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: