How can I get this dynamic WHERE statement in my LINQ-to-XML to work?
- by Edward Tanguay
In this question Jon Skeet offered a very interesting solution to making a LINQ-to-XML statement dynamic, but my knowledge of lambdas and delegates is not yet advanced enough to implement it:
I've got it this far, but of course I get the error "smartForm does not exist in the current context":
private void LoadWithId(int id)
{
XDocument xmlDoc = null;
try
{
xmlDoc = XDocument.Load(FullXmlDataStorePathAndFileName);
}
catch (Exception ex)
{
throw new Exception(String.Format("Cannot load XML file: {0}", ex.Message));
}
Func<XElement, bool> whereClause = (int)smartForm.Element("id") == id";
var smartForms = xmlDoc.Descendants("smartForm")
.Where(whereClause)
.Select(smartForm => new SmartForm
{
Id = (int)smartForm.Element("id"),
WhenCreated = (DateTime)smartForm.Element("whenCreated"),
ItemOwner = smartForm.Element("itemOwner").Value,
PublishStatus = smartForm.Element("publishStatus").Value,
CorrectionOfId = (int)smartForm.Element("correctionOfId"),
IdCode = smartForm.Element("idCode").Value,
Title = smartForm.Element("title").Value,
Description = smartForm.Element("description").Value,
LabelWidth = (int)smartForm.Element("labelWidth")
});
foreach (SmartForm smartForm in smartForms)
{
_collection.Add(smartForm);
}
}
Ideally I want to be able to just say:
var smartForms = GetSmartForms(smartForm=> (int) smartForm.Element("DisplayOrder").Value > 50);
I've got it this far, but I'm just not grokking the lambda magic, how do I do this?
public List<SmartForm> GetSmartForms(XDocument xmlDoc, XElement whereClause)
{
var smartForms = xmlDoc.Descendants("smartForm")
.Where(whereClause)
.Select(smartForm => new SmartForm
{
Id = (int)smartForm.Element("id"),
WhenCreated = (DateTime)smartForm.Element("whenCreated"),
ItemOwner = smartForm.Element("itemOwner").Value,
PublishStatus = smartForm.Element("publishStatus").Value,
CorrectionOfId = (int)smartForm.Element("correctionOfId"),
IdCode = smartForm.Element("idCode").Value,
Title = smartForm.Element("title").Value,
Description = smartForm.Element("description").Value,
LabelWidth = (int)smartForm.Element("labelWidth")
});
}