using variables in a dynamic linq query

blub picture blub · May 1, 2012 · Viewed 20.6k times · Source

I am using Linq to Entities and have added the using stmt of using System.Linq.Dynamic; My goal is to pass in the whereClause variable into the emailList query (see screen shot).

Any thoughts?

Error message details

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
After using @Michael suggestion I got it to work with the following:

HTML (notice I placed the field value in 'Value' attr.):

<asp:CheckBoxList ID="_checkboxGroups" runat="Server">
                            <asp:ListItem Text="Sid Dickens Lovers" Value="SidDickens_TF" Selected="False" />
                            <asp:ListItem Text="Rosamond Lover" Value="Rosamond_TF" Selected="false" />
                            <asp:ListItem Text="Wine and Cheese Lovers" Value="WineAndCheese_TF" Selected="false" />
                            <asp:ListItem Text="Good Clients" Value="IntDesign_TF" Selected="false" />
                            <asp:ListItem Text="Vendors" Value="Vendor_TF" Selected="false" />
                        </asp:CheckBoxList>

Code behind:

// determine # of items in asp:CheckBoxList
        var groupCount = _checkboxGroups.Items.Count;

        var conditions = new List<string>();

        for (int i = 0; i < groupCount; i++)
        {
            if (_checkboxGroups.Items[i].Selected)
            {
                conditions.Add(_checkboxGroups.Items[i].Value.ToString() + " == true");
            }
        }

        string whereClause = string.Join(" OR ", conditions.ToArray());


        ElanEntities3 db = new ElanEntities3();

        var emailList = (from c in db.vEmailListViewforSendings
                         orderby c.Email
                         select c).AsQueryable();

        emailList = emailList.Where(whereClause);

       _listViewClients.DataSource = emailList;

Answer

Nick Butler picture Nick Butler · May 1, 2012

You need to pass an object that matches the parameter to IQueryable.Where( predicate )

So whereClause must be an object of this type:

Expression<Func<TSource, bool>>

Because you are ORing your where clauses not ANDing them, you will have to build one big where clause.

Assuming your data object is of type OBJ and it has bool properties P0 and P1:

bool filterP0 = _checkboxGroups[0].Selected;
bool filterP1 = _checkboxGroups[1].Selected;

Expression<Func<OBJ, bool>> predicate = o =>
(
    ( !filterP0 && !filterP1 )
    ||
    ( filterP0 && o.P0 )
    ||
    ( filterP1 && o.P1 )
);

var emailList =
    db.vEmailListViewForSendings
        .Where( predicate )
        .OrderBy( o => o.ID );

That's the gist anyway.


Or, if you really must build the predicate dynamically, you could use Joe Albahari's Predicate Builder.