2010-08-17 46 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使用延迟执行,并且只会在实际使用输出的地方执行。与此同时,不断建立表达树。你拥有的是完全可读的。如果你认为它更具可读性,我只会改变它。