LINQ, parsing and error handling
-
I am reading data from an XML using LINQ. Some elements contains data that I want to parse to a specific object type, say for example they are numbers that I want to parse to integers. If the data in one element is incorrect (i.e. "abc" where there should be a number) I just want to skip it and read the rest (meaning a try...catch around the entire LINQ would not work). If I were using loops I would just use a try...catch around the Parse method, with a
continue;
in the catch. But how do I accomplish this using LINQ? One solution is to use TryParse in a where statement, but then I have to parse the text twice, first with TryParse in the where, and then with Parse in select. Ok, parsing an integer might be cheap, but say: *There is no TryParse for the object I want, only a Parse method throwing exceptions (ok, I could write a TryParse wrapper) or *The parsing is not cheap for the specific object type I want, and it would be a major performance hog having to do it twice. How would I go about doing this? -
I am reading data from an XML using LINQ. Some elements contains data that I want to parse to a specific object type, say for example they are numbers that I want to parse to integers. If the data in one element is incorrect (i.e. "abc" where there should be a number) I just want to skip it and read the rest (meaning a try...catch around the entire LINQ would not work). If I were using loops I would just use a try...catch around the Parse method, with a
continue;
in the catch. But how do I accomplish this using LINQ? One solution is to use TryParse in a where statement, but then I have to parse the text twice, first with TryParse in the where, and then with Parse in select. Ok, parsing an integer might be cheap, but say: *There is no TryParse for the object I want, only a Parse method throwing exceptions (ok, I could write a TryParse wrapper) or *The parsing is not cheap for the specific object type I want, and it would be a major performance hog having to do it twice. How would I go about doing this?You could write a "ParseOrDefault" method that returns null when the parsing fails and check for null when you iterate the collection. Instead of the null check when you iterate, you could also use the Where method to filter the query results.
YourObj ParseOrDefault(string s)
{
try
{
return YourObj.Parse(s);
}
catch (Exception e)
{
return null;
}
} -
You could write a "ParseOrDefault" method that returns null when the parsing fails and check for null when you iterate the collection. Instead of the null check when you iterate, you could also use the Where method to filter the query results.
YourObj ParseOrDefault(string s)
{
try
{
return YourObj.Parse(s);
}
catch (Exception e)
{
return null;
}
}