This question starts here: Dynamic LINQ to SharePoint and Projection

how to build dynamic LINQ to SharePoint expression like this(but store "Bill", "Sam" in array):

// Listing 1

// SPEntityModelDataContext generated with SPMetal
using (var db = new SPEntityModelDataContext("http://sharepoint/"))
    var res = db.OrgUnitToUser
        .Where(oo => (oo.User.Title == "Bill" || oo.User.Title == "Sam") 
            || [any condition we want])

Using BuildOrExpressionEqual method we can finde all users with names stored in array:

// Listing 2

private static Expression<Func<TElement, bool>> BuildOrExpressionEqual<TElement, TValue>(Expression<Func<TElement, TValue>> valueSelector, IEnumerable<TValue> values)
    if (null == valueSelector)
        throw new ArgumentNullException("valueSelector");
    if (null == values)
        throw new ArgumentNullException("values");

    var p = valueSelector.Parameters.Single();

    if (!values.Any())
        return e => false;

    var equals =
        values.Select(value =>
            (Expression)Expression.Equal(valueSelector.Body, Expression.Constant(value, typeof(TValue))));

    var body = equals.Aggregate<Expression>((accumulate, equal) => Expression.Or(accumulate, equal));

    return Expression.Lambda<Func<TElement, bool>>(body, p);

// usage

var names = new string[] {"Bill", "Sam"};

using (var db = new SPEntityModelDataContext("http://sharepoint/"))
    var res = db.OrgUnitToUser
        .Where(BuildOrExpressionEqual<OrgUnitToUserItem, string>(tt => tt.User.Title, names))

But how to add [any condition we want] (see Listing 1)?

  • Wouldn't you just build a method that accepts an array of users and returns a boolean? Then you can just pass oo to the function to check.
    – Kit Menke
    Feb 22, 2012 at 1:01

1 Answer 1


Try using the LINQ Dynamic Query Library. A class file (Dynamic.cs) is provided by MS in their C# samples. Reference that in your project. It extends LINQ so that we can use strings for Where expressions. This lets us compose query at runtime.

Here is an article which I found to be helpful when I was working on a similar problem: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.