LINQ查询语法中的预定义表达式

时间:2013-07-05 15:56:41

标签: c# linq entity-framework expression linq-query-syntax

是否可以在expression的LINQ表达式中使用先前定义的query syntax?我创造了一个人为的例子来说明我的问题。

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; }
}

我正在使用C#5和EF 5。

1 个答案:

答案 0 :(得分:0)

您可以使用where isTablet.Compile()(c)。您可能希望缓存已编译的版本。