I have no idea what this exception is. Just when I thought I was getting the hang of linq something like this happens. I am getting this exception:
Unable to cast object of type 'WhereSelectEnumerableIterator`2[System.Xml.Linq.XElement,TestImplementationIdeas.PatientClass]' to type 'TestImplementationIdeas.PatientClass'.
Now, I have know idea why this exception is being throw.
PatientClass template = (PatientClass)(from templates in xDocument.Descendants("template").Where
(templates => ((templates.Descendants("element").Attributes("name").ToString() == "EncounterId") && templates.Descendants("element").Attributes("value").ToString() == Enc.ToString())) //elem.XPathSelectElements(string.Format("//templates/template[./elements/element[@name=\"PopulationPatientID\"and @value='{0}' and @enc='{1}']]",PopulationPatID, Enc))
select new PatientClass
{
PatientId = Convert.ToInt32("0" + templates.XPathSelectElement("elements/element[@name='PatientId']").Attribute("value").Value),
EMPIID = Convert.ToInt32("0" + templates.XPathSelectElement("elements/element[@name='EMPIID']").Attribute("value").Value),
//public int PopulationPatientID { get; set; }
FirstName = templates.XPathSelectElement("elements/element[@name='FirstName']").Attribute("value").Value,
LastName = templates.XPathSelectElement("elements/element[@name='LastName']").Attribute("value").Value,
});
return template != null ? template : null;
In general, LINQ queries always return an
IEnumerable<>object, in your case,IEnumerable<PatientClass>. You need to perform additional opertions to filter a collection to a single object.And instead of the
OrDefault()methods, if you want to control what value is returned when it is empty, there is aDefaultIfEmpty<>()extension method that you can specify a value if the collection is empty.