I’m using the following code to load a list of objects from XML using LINQ:
List<Order> TheList =
(from order in XMLResponse.Descendants("Order")
select new Order
{
OrderDate = DateTime.Parse(order.Element("OrderDate").Value)
}).ToList<Order>();
I would like to use DateTime.TryParse so that I can use DBNull values on the values that do not parse correctly so I can continue processing if there is an error. I’ve tried this:
OrderDate = DateTime.TryParse(order.Element("OrderDate").value, out OrderDate)
But that code yields an invalid argument exception.
I know I could use an intermediary class (with all string values) to load the values, but that seems like excessive code for what I’m trying to accomplish. Is there a way to use TryParse in my code above? Thanks
Assuming this is an appropriately formatted date for XML, you can cast to
DateTime?:That will still throw an exception if the value is bad, but return the null value if it’s missing.
Admittedly I wouldn’t expect that to actually compile, as you’re not selecting an
Order… but you see what I mean.Here’s an alternative which uses
TryParse:This basically gives an alternative form of
TryParsewhich uses aNullable<DateTime>instead of a separate Boolean flag to allow it to indicate parse failures.I would strongly recommend that you use
TryParseExactwith an appropriate format string and culture, by the way.