XML LINQ Select to Object - Using TryParse
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?
:
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 = TryParseDateTime(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.
internal class DateTimeParse
{
public DateTimeParse(string str)
{
DateTime dt = DateTime.MinValue;
Correct = DateTime.TryParse(str, out dt);
if (Correct) Value = dt;
}
public DateTime Value { get; private set; }
public bool Correct { get; private set; }
}
.
var hist = from x in aNodes
let dt = new DateTimeParse(x.InnerHtml)
where dt.Correct
select dt.Value;
The problem here is that DateTime.Tryparse
like almost all TryParse
returns a Boolean value.
The OUT parameter here is a DateTime
(not nullable).
It's like:
bool myBool = Datetime.TryParse(myString, out myDateTimeNotNullable);
You can also use it nested in a validation:
if(Datetime.TryParse(myString, out myDateTimeNotNullable))
{
//myDateTimeNotNullable has the valid DateTime from myString
}
else
{
//myDateTimeNotNullable has the value set to new DateTime()
}
That's what I would write:
DateTime OrderDate;
DateTime.TryParse(((XmlNode)order.Element("OrderDate")).InnerText, out OrderDate);
I hope it helps someone, since it's an old post.
精彩评论