简体   繁体   中英

c# linq to xml dynamic query

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

Just use the normal Boolean operators && and ||:

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

That's just a direct translation of the original code - but I think you'll want a cast from vals.Element("CustomerID") to int , and you don't really want to convert textbox1.Text on every iteration, I'm sure. You also need to convert the "name" XElement to a string. How about this:

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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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