c#linq to xml动态查询

时间:2010-04-14 08:39:22

标签: c# xml linq linq-to-xml

对,一个奇怪的问题;我最近一直在做一些linq to XML工作(请参阅我最近的其他帖子herehere)。

基本上,我希望能够创建一个查询,检查文本框在查询中包含值之前是否为null,如下所示:

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();

1 个答案:

答案 0 :(得分:1)

只需使用普通的布尔运算符&&和||:

XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
            where (textbox1.Text != "" && 
               vals.Element("CustomerID") == Convert.ToInt32(textbox1.Text)) || 
               (textbox2.Text != "" && vals.Element("Name") == textbox2.Text)
            select vals).ToList();

这只是原始代码的直接翻译 - 但我认为您需要从vals.Element("CustomerID")转换为int,而您实际上并不想转换textbox1.Text每次迭代,我都很有信心。您还需要将“名称”XElement转换为字符串。怎么样:

int? customerId = null;
if (textbox1.Text != "")
{
    customerId = int.Parse(textbox1.Text);
}

XDocument db = XDocument.Load(xmlPath);
var query = (from vals in db.Descendants("Customer")
             where (customerId != null && 
                (int) vals.Element("CustomerID") == customerId) ||
                (textbox2.Text != "" && 
                 (string) vals.Element("Name") == textbox2.Text)
             select vals).ToList();

或者,您可以将查询的两个部分分开,并将结果“联合”在一起。或者 - 最好是IMO - 您可以更动态地构建查询:

var query = db.Descendants("Customer");
if (textbox1.Text != null)
{
    int customerId = int.Parse(textbox1.Text);
    query = query.Where(x => (int) x.Element("CustomerID") == customerId);
}

if (textbox2.Text != null)
{
    query = query.Where(x => (string) x.Element("Name") == textbox2.Text);
}
List<XElement> results = query.ToList();