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 ||:
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.Texton every iteration, I’m sure. You also need to convert the “name”XElementto 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: