I have a simple LINQ-expression like:
newDocs = (from doc in allDocs
where GetDocument(doc.Key) != null
select doc).ToList();
The problem is, GetDocument() could throw an exception. How can I ignore all doc-elements where GetDocument(doc.Key) == null or throws an exception?
The same code in old school looks like:
foreach (var doc in allDocs)
{
try
{
if (GetDocument(doc.Key) != null) newDocs.Add(doc);
}
catch (Exception)
{
//Do nothing...
}
}
allDocs.Where(doc => {
try {
return GetDocument(doc.Key) != null;
} catch {
return false;
}
}).ToList();
I'm not sure it's possible using query comprehension syntax, except via some baroque atrocity like this:
newDocs = (from doc in allDocs
where ((Predicate<Document>)(doc_ => {
try {
return GetDocument(doc_.Key) != null;
} catch {
return false;
}
}))(doc)
select doc).ToList();
A linq extension can be written to skip all elements that cause an exception. See this stackoverflow post
public static IEnumerable<T> CatchExceptions<T> (this IEnumerable<T> src, Action<Exception> action = null) {
using (var enumerator = src.GetEnumerator()) {
bool next = true;
while (next) {
try {
next = enumerator.MoveNext();
} catch (Exception ex) {
if (action != null) {
action(ex);
}
continue;
}
if (next) {
yield return enumerator.Current;
}
}
}
}
Example:
ienumerable.Select(e => e.something).CatchExceptions().ToArray()
ienumerable.Select(e => e.something).CatchExceptions((ex) => Logger.Log(ex, "something failed")).ToArray()
posting this here in case anyone else finds this answer first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With