2010-08-17 43 views
1

是否可以將下面的linq查詢合併到一個查詢中?在linq查詢中篩選所選可枚舉項

var checkBoxes = from x in FindAll<CheckBox>() 
       where x.Checked 
       select new 
       { 
        RecordType = Type.GetType(x.Attributes["RecordType"]), 
        RecordId = Int32.Parse(x.Attributes["RecordId"]) 
       }; 

checkBoxes = from x in checkBoxes 
      where x.RecordType != typeof(DomainModel.Group) 
      select x; 

回答

5
var checkBoxes = from x in FindAll<CheckBox>() 
       let recordType = Type.GetType(x.Attributes["RecordType"]) 
       where x.Checked && recordType != typeof(DomainModel.Group) 
       select new 
       { 
        RecordType = recordType, 
        RecordId = Int32.Parse(x.Attributes["RecordId"]) 
       }; 
+0

啊。當然:) 感謝您的快速回復! – asgerhallas 2010-08-17 09:16:49

+0

它將在8分鐘內被接受。 – asgerhallas 2010-08-17 09:17:08

+0

使用let關鍵字是個好主意。順便說一句,我們可以在泛型linq表達式中使用一些方法,如「let」關鍵字?看到我的答案。 – 2010-08-17 09:20:30

0
var checkboxes = FindAll<CheckBox>() 
        .Where(x => x.Checked && Type.GetType(x.Attributes["RecordType"]) != typeof(DomainModel.Group)) 
        .Select(new{ 
          RecordType = Type.GetType(x.Attributes["RecordType"]), 
          RecordId = Int32.Parse(x.Attributes["RecordId"]) 
        }); 
3

lasseespeholt的答案是非常好的(最好,甚至是 - 有在做的,如果你要扔掉結果的投影沒有意義),但如果你想申請這更通常,你可以使用一個查詢延續

var checkBoxes = from x in FindAll<CheckBox>() 
       where x.Checked 
       select new 
       { 
        RecordType = Type.GetType(x.Attributes["RecordType"]), 
        RecordId = Int32.Parse(x.Attributes["RecordId"]) 
       } into y 
       where y.RecordType != typeof(DomainModel.Group) 
       select y; 

在這裏,我已經改變了第二個變量來自xy說清楚它與原始的x不同,但你不必這樣做。

從而避免了調用Type.GetType兩次,但還是把where子句前的最後投影使用let條款(其中引入了另一個投影本身,無可否認),另一種選擇:

var checkBoxes = from x in FindAll<CheckBox>() 
       where x.Checked 
       let t = Type.GetType(x.Attributes["RecordType]") 
       where t != typeof(DomainModel.Group) 
       select new 
       { 
        RecordType = t 
        RecordId = Int32.Parse(x.Attributes["RecordId"]) 
       }; 
+0

+1對於「select ... into ...」。就我個人而言,我認爲沒有「讓」在「where」子句裏面更漂亮。 – 2010-08-17 09:21:11

+0

@lasseespeholt:它真的在where子句中「內部」 - 有兩個where子句和一個let子句,都是獨立的。 – 2010-08-17 09:32:07

+0

對不起,我英文不對。我的意思是在=之間:) – 2010-08-17 09:41:31

0

爲什麼你想變成一個linq查詢? Linq使用延遲執行,並且只會在實際使用輸出的地方執行。與此同時,不斷建立表達樹。你擁有的是完全可讀的。如果你認爲它更具可讀性,我只會改變它。