Exception handling within a LINQ Expression

Rocco Hundertmark picture Rocco Hundertmark · Dec 1, 2010 · Viewed 20.9k times · Source

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...
                }
            }

Answer

Marcelo Cantos picture Marcelo Cantos · Dec 1, 2010
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();