Linq查询中的异常处理

Nit*_*tin 3 c# linq exception-handling try-catch

我正在使用 ...

tmpLst = (from e in App.lstAllChilds where e.Id == Id select e).ToList();
Run Code Online (Sandbox Code Playgroud)

lstAllChilds列表在哪里,其中包含一些损坏的数据.

所以现在我要在这个查询中处理Try-Catch块.
请帮忙.

小智 9

如果你只是想忽略"坏元素",那么:

App.lstAllChilds.SkipExceptions().Where( e => e.Id == Id).ToList();
Run Code Online (Sandbox Code Playgroud)

扩展方法:

 public static class Extensions
    {
        public static IEnumerable<T> SkipExceptions<T>(this IEnumerable<T> values)
        {
            using (var enumerator = values.GetEnumerator())
            {
                bool next = true;
                while (next)
                {
                    try
                    {
                        next = enumerator.MoveNext();
                    }
                    catch
                    {
                        continue;
                    }

                    if (next) yield return enumerator.Current;
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)