我有一个简单的 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/