c# - LINQ 表达式中的异常处理

标签 c# linq-to-objects

我有一个简单的 LINQ 表达式,例如:

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

问题是,GetDocument() 可能会抛出异常。如何忽略所有 GetDocument(doc.Key) == null 或抛出异常的文档元素?

旧学校的相同代码如下:

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

我不确定是否可以使用查询理解语法,除非通过像这样的巴洛克式暴行:

newDocs = (from doc in allDocs
           where ((Predicate<Document>)(doc_ => {
               try {
                   return GetDocument(doc_.Key) != null;
               } catch {
                   return false;
               }
           }))(doc)
           select doc).ToList();

关于c# - LINQ 表达式中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4322542/

相关文章:

c# - C# : What is the purist way of achieving what I am trying to do? 中的多重继承

c# - 如何使用 Linq to objects 按固定数量对我的选择进行分组?

c# - 如何验证对象列表中的值?

linq - LINQ(对象)何时过度使用?

c# - 依赖于 LinqToObjects 的自定义 IQueryProvider

c# - NHibernate IQueryable.SingleOrDefault 在子查询中。使用函数谓词而不执行

c# - 使用 iText7 + C# 从 pdf 读取文本,无法识别文本

c# - 中断 native 线程

C# TCP 服务器不可靠,丢弃过时的缓冲消息

c# - 使用 LINQ 在列表中智能迭代