是否可以将下面的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;
答案 0 :(得分: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"])
};
答案 1 :(得分: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;
我已将第二个变量从x
更改为y
,以明确它与原始x
不同,但您不必这样做。< / p>
另一个避免调用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"])
};
答案 2 :(得分: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 :(得分:0)
为什么要更改为一个linq查询? Linq使用延迟执行,只有在您实际使用输出时才会执行。在平均时间内不断构建表达式树。你拥有的是完全可读的。如果你认为它更具可读性,我只会改变它。