动态组合LINQ表达式

时间:2013-01-11 09:27:24

标签: c# linq linq-to-nhibernate

是否可以组合动态表达式:

from c in collection where c.Property == true select c

带表达式

from result in results 
group result by result.Property 
into g 
select new g.Key 

其中'results'应该是从第一个表达式返回的集合?

我将使用组合表达式使用NHibernate从db获取数据,所以我希望组合表达式等于我是否将它写为

from c in collection 
where c.Property == true
group c by c.Property
into g
select new g.Key

表达式在类中定义:

public class MyClass : MyAbstractClass<User>
{
    public MyClass()
    {
        FirstExpression = users => from user in users where ... select user;              

        SecondExpression = results => from result in results
                       group result by result.Property into g
                       select g.Key

    }
}

2 个答案:

答案 0 :(得分:1)

var query = collection;

if (condition)
    query = query.Where(c => c.Property);

var result = query.GroupBy(c => c.Property).Select(g => g.Key);

答案 1 :(得分:0)

是的,这是可能的。只需将第一个查询的结果分配给results变量,而不进行枚举:

var results = from c in collection where c.Property == true select c;

from result in results 
group result by result.Property 
into g 
select g.Key; 

BTW,您的第二个查询是一个简单的distinct

results.Distinct(r => r.Property);