0

Is it possible to combine dynamically expressions:

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

with expression

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

where 'results' should be the collection returned from first expression ?

I am going to use composed expression to fetch the data from db using NHibernate, so I would like the combined expression to be equal to if I would write it as

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

The expressions are defined in the class:

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

    }
}
4

2 回答 2

1
var query = collection;

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

var result = query.GroupBy(c => c.Property).Select(g => g.Key);
于 2013-01-11T09:30:05.157 回答
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; 

顺便说一句,您的第二个查询很简单distinct

results.Distinct(r => r.Property);
于 2013-01-11T09:29:33.080 回答