繁体   English   中英

在linq查询中筛选选定的可枚举

[英]Filter on the selected enumerable in a linq query

是否可以将下面的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;
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"])
                 };

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;

在这里,我将第二个变量从x更改为y ,以使其清楚与原始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"])
                 };
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"])
                  });

您为什么要更改为一个linq查询? Linq使用延迟执行,并且仅在您实际在某处使用输出时才执行。 同时,不断建立表达式树。 您所拥有的完全可读。 如果您认为它更具可读性,我只会对其进行更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM