Archive

Posts Tagged ‘in’

Linq “in” clause

July 14, 2011 Leave a comment

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: , , , ,