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开发者_如何学Go 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();
精彩评论