【问题标题】:Expression Tree as part of a Property作为属性一部分的表达式树
【发布时间】:2012-02-11 13:39:31
【问题描述】:

我从这个问题中汲取灵感:

Convert Linq to Sql Expression to Expression Tree

原发帖人询问如何将其转换为表达式树并得到了很好的答案,可以在上面的链接中看到。

List<Region> lst = (from r in dc.Regions
                    where r.RegionID > 2 && r.RegionDescription.Contains("ern")
                    select r).ToList();

如何使用 get 方法创建一个属性,该方法返回一个使用 ExpressionTree 的布尔值?我希望能够做这样的事情(显然我不需要== true):

List<Region> lst = (from r in dc.Regions
                    where (r.AwesomeProperty == true)
                    select r).ToList();

我将如何定义AwesomeProperty

【问题讨论】:

    标签: c# linq c#-4.0


    【解决方案1】:

    您可以像定义 LINQ to SQL 对象上的任何其他属性一样定义 AwesomeProperty。假设它的类型为bool(因为您将其与true 进行比较),您将构建Where 查询,如下所示:

    // Build the parameter to the where clause predicate and access AwesomeProperty
    
    var regionParameter = Expression.Parameter(typeof(Region), "region");
    
    var awesomeProperty = Expression.Property(regionParameter, "AwesomeProperty");
    
    // Build the where clause predicate using the AwesomeProperty access
    
    var predicate = Expression.Lambda<Func<Region, bool>>(awesomeProperty);
    
    // Get the table, which serves as the base query
    
    var table = dc.Regions.AsQueryable();
    
    // Call the Where method using the predicate and the table as the base query
    
    var whereCall = Expression.Call(
        typeof(Queryable),
        "Where",
        new[] { table.ElementType },
        table.Expression,
        predicate);
    
    // Get an IQueryable<Region> which executes the where call on the table
    
    var query = table.Provider.CreateQuery<Region>(whereCall);
    
    var results = query.ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-05
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多