tags:

views:

98

answers:

2

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

+2  A: 

Assuming this is an appropriately formatted date for XML, you can cast to DateTime?:

from order in XMLResponse.Descendants("Order")
select new obj
{
    OrderDate = (DateTime?) order.Element("OrderDate")
}).ToList<Order>();

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:

public static DateTime? TryParseDateTime(string value)
{
    DateTime ret;
    return DateTime.TryParse(value, out ret) ? ret : (DateTime?) null;
}
...
List<Order> list = from order in XMLResponse.Descendants("Order")
                   select new obj
                   {
                       OrderDate = TryParse(order.Element("OrderDate").Value)
                   }).ToList<Order>();

This basically gives an alternative form of TryParse which uses a Nullable<DateTime> instead of a separate Boolean flag to allow it to indicate parse failures.

I would strongly recommend that you use TryParseExact with an appropriate format string and culture, by the way.

Jon Skeet
exactly what I needed, thanks Jon
bvanderhaar
I should mention I had to change the return line in the TryParseDateTime method to include the second parameter - like this: DateTime.TryParse(value, out ret) ? ret : (DateTime?) null;
bvanderhaar
@bvanderhaar: Whoops, yes :) Will fix.
Jon Skeet