SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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)?

share|improve this question
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 '12 at 1:01
up vote 0 down vote accepted

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:

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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