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();