Andy Clarke
Andy Clarke

Reputation: 3262

How can I incorporate an Expression<Func<T, TPropertyType>> into my IQueryable?

I added a method to our Service Base Class to get all unexported instances of a particular item (an Item of type T)

    public virtual IEnumerable<T> UnexportedToSun()
    {
        var query = GetIQueryable();
        query = query.Where(x => x.SunExportDate == null);
        return query.ToList();
    }

This has worked well ... however we've got a couple of new cases where we need to pass in a bit of a query.

What I wanted to do was use the

Expression<Func<T, TPropertyType>> 

syntax so that I could do stuff like this ...

var transportInvoices = _purchaseInvoiceService.UnexportedToSun(x => x.InvoiceType == InvoiceType.Transport);

The above worked as I imagined ... but I'm not sure where to go now ...

    public virtual IEnumerable<T> UnexportedToSun<TPropertyType>(Expression<Func<T, TPropertyType>> otherQuery)
    {
        var query = GetIQueryable();
        query = query.Where(x => x.SunExportDate == null);
        query = query //TODO: Add my other query
        return query.ToList();
    }

Can anyone point me in the right direction please?

Upvotes: 1

Views: 233

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501656

If you just need to add more filters, you can call Where again:

var query = GetIQueryable();
query = query.Where(x => x.SunExportDate == null);
query = query.Where(x => x.IsHappy);
return query.ToList();

That's one of LINQ's nice feature's - it's composable, so you can build up block by block. You could do other things, too... for example:

var query = GetIQueryable();
query = query.Where(x => x.SunExportDate == null);
query = query.Select(x => x.ValueA + x.ValueB);
return query.ToList(); // Will return a List<int> or whatever instead

For a general purpose filter, you'd want an expression returning bool::

public virtual IEnumerable<T> UnexportedToSun(Expression<Func<T, bool>> predicate)
{
    var query = GetIQueryable();
    query = query.Where(x => x.SunExportDate == null);
    query = query.Where(predicate);
    return query.ToList();
}

Upvotes: 3

Related Questions