22

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

5 Answers 5

24
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();
0
20

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.

14

You can move the whole try catch block and GetDocument call to another method

Document TryGetDocument(string key)
{
         try
         {
            if (GetDocument(doc.Key) != null) 
              return doc;
         }
         catch (Exception)
         {
             return null;
         }
     return null;
}

and then use this function in your query -

newDocs = (from doc in allDocs
       where TryGetDocument(doc.Key) != null
       select doc).ToList();

This will keep your query concise and easy to read.

0
4

Have you tried the Expression.TryCatch

IEnumerable<string> allDocs = new List<string>();
var newDocs = (from doc in allDocs
                    where Expression.TryCatch(
                          Expression.Block(GetDocument(doc.key)),
                          Expression.Catch(typeof(Exception),null)) != null                                 
                          select doc).ToList();

TryExpression msdn

1

Write your own method. MyGetDocument( ) that will handle the exception and call it from LINQ.

newDocs = (from doc in allDocs
       where MyGetDocument(doc.Key) != null
       select doc).ToList();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.