时间:2019-03-17 标签:c#linqtoxml动态查询
是的,有点奇怪的问题;我最近一直在做一些 linq to XML 工作(请参阅我最近的其他帖子 此处 和此处)。
基本上,我希望能够创建一个查询,在文本框的值包含在查询中之前检查文本框是否为空,如下所示:
XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
where (if(textbox1.Text != "") {vals.Element("CustomerID") == Convert.ToInt32(textbox1.Text) } ||
if(textbox2.Text != "") {vals.Element("Name") == textbox2.Text})
select vals).ToList();
Right, bit of a strange question; I have been doing some linq to XML work recently (see my other recent posts here and here).
Basically, I want to be able to create a query that checks whether a textbox is null before it's value is included in the query, like so:
XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
where (if(textbox1.Text != "") {vals.Element("CustomerID") == Convert.ToInt32(textbox1.Text) } ||
if(textbox2.Text != "") {vals.Element("Name") == textbox2.Text})
select vals).ToList();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需使用普通的布尔运算符 &&和 ||:
这只是原始代码的直接翻译 - 但我认为您需要从
vals.Element("CustomerID")
到int
的转换,并且我确信你并不真的想在每次迭代时都转换textbox1.Text
。您还需要将“名称”XElement
转换为字符串。怎么样:或者,您可以将查询的两个部分分开,并将结果“联合”在一起。或者 - 最好是 IMO - 您可以更动态地构建查询:
Just use the normal Boolean operators && and ||:
That's just a direct translation of the original code - but I think you'll want a cast from
vals.Element("CustomerID")
toint
, and you don't really want to converttextbox1.Text
on every iteration, I'm sure. You also need to convert the "name"XElement
to a string. How about this:Alternatively, you could separate out the two parts of the query and "union" the results together. Or - preferably IMO - you could build the query more dynamically: