2013-01-11 99 views
0

是否可以動態地結合表達式:動態撰寫LINQ表達式

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 

其中「結果」應該是集合從第一表達式返回?

我將使用由表達式從分貝使用NHibernate獲取數據,所以我想聯合表達爲等於我是否寫爲

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 

    } 
} 

回答

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); 
+0

OK,但如果兩個表達式是該類的屬性,例如FirstExpression和SecondExpression? –

+0

@ petrov.alex:請嘗試重新修飾這句話,它不會像現在這樣表達太多意思。表達式通常不是一個類的屬性 - 表達式是使用*類的屬性書寫的。 –

+0

我已經更新的問題,請檢查是否有意義現在 –

1
var query = collection; 

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

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