构建“何处” Linq 查询中的子句
在此查询中,我始终需要“正常”类型元素。
如果设置了 _includeX 标志,我也需要“工作空间”类型元素。
有没有一种方法可以将其写为一个查询? 或者在提交查询之前基于_includeX构建where子句?
if (_includeX) {
query = from xElem in doc.Descendants(_xString)
let typeAttributeValue = xElem.Attribute(_typeAttributeName).Value
where typeAttributeValue == _sWorkspace ||
typeAttributeValue == _sNormal
select new xmlThing
{
_location = xElem.Attribute(_nameAttributeName).Value,
_type = xElem.Attribute(_typeAttributeName).Value,
};
}
else {
query = from xElem in doc.Descendants(_xString)
where xElem.Attribute(_typeAttributeName).Value == _sNormal
select new xmlThing
{
_location = xElem.Attribute(_nameAttributeName).Value,
_type = xElem.Attribute(_typeAttributeName).Value,
};
}
In this query, I always want the 'normal' type element.
If the _includeX flag is set, I want the 'workspace' type elements, too.
Is there a way to write this as one query? Or build the where clause based on _includeX before submitting the query?
if (_includeX) {
query = from xElem in doc.Descendants(_xString)
let typeAttributeValue = xElem.Attribute(_typeAttributeName).Value
where typeAttributeValue == _sWorkspace ||
typeAttributeValue == _sNormal
select new xmlThing
{
_location = xElem.Attribute(_nameAttributeName).Value,
_type = xElem.Attribute(_typeAttributeName).Value,
};
}
else {
query = from xElem in doc.Descendants(_xString)
where xElem.Attribute(_typeAttributeName).Value == _sNormal
select new xmlThing
{
_location = xElem.Attribute(_nameAttributeName).Value,
_type = xElem.Attribute(_typeAttributeName).Value,
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将其分解为一个单独的谓词:
或内联条件:
或删除查询表达式用法并按以下方式执行:-
或将第一个和第三个组合起来并执行以下操作:
这完全取决于在您的上下文中最干净的工作方式。
帮自己一个忙,购买(并阅读!)《C# 深度》,这比一点一点地学习这些东西更快地变得有意义......
You can break it into a separate predicate:
Or inline the condition:
Or remove query expression usage and do it this way:-
Or combine the first and third and do:
It all depends what's going to work cleanest in your context.
Do yourself a favour and buy (and read!) C# in Depth and it'll all make sense a lot more quickly that learning this stuff bit by bit...