Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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])
        .ToList();
}

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))
        .ToList();
}

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
add comment

1 Answer 1

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: http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx

share|improve this answer
add comment

Your Answer

 
discard

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.