Search code examples
c#linqexceptiontry-catch

Exception handling in Linq queries


I m using ...

tmpLst = (from e in App.lstAllChilds where e.Id == Id select e).ToList();

where lstAllChilds is the list, which contains some corrupted data as well.

So now i m tying to handle Try-Catch block inside this query.
Please help.


Solution

  • Here is the simplest change you can make to simply exclude items which are null or are raising an exception.

    tmpLst = App.lstAllChilds.Where(e =>
    {
        try
        {
            return e != null && e.Id == Id;
        }
        catch
        {
            return false;
        }
    }).ToList();
    

    But in my opinion you probably should investigate and solve the underlying problem. This doesn't seem like a scenario where exceptions should be expected.