1

Is it possible to use a previously defined expression in LINQ expressions with query syntax? I've created a contrived example to illustrate my question.

var tabletTypes = new List<int> { 2, 3 };
//I want to use this expression many times
Expression<Func<Computer, bool>> isTablet = comp => tabletTypes.Contains(comp.Type);

var computers = db.Computers;
var producers = db.Producers;

//I know how to use the expression in fluent syntax
IQueryable<Producer> tabletProducers = computers
                               .Where(isTablet)
                               .Join(producers, 
                                     comp => comp.ProducerId, 
                                     producer => producer.Id, 
                                     (comp, producer) => producer);

//How can I use the expression in query syntax
IQueryable<Producer> tabletProducers2 = from c in computers
                                        join p in producers
                                            on c.ProducerId equals p.Id
                                        where /*How can I use isTablet here?*/
                                        select p;


public class Producer
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class Computer
{
    public int Id { get;set; }
    public int Type { get; set; }
    public int ProducerId { get; set; }
}

I am using C# 5 and EF 5.

Steven Wexler
  • 16,589
  • 8
  • 53
  • 80

1 Answers1

0

You can just use where isTablet.Compile()(c). You might want to cache the compiled version.

Rob
  • 4,327
  • 6
  • 29
  • 55