在IEnumerable.First功能,如果没有匹配,我该如何处理?目前它只是崩溃......
MySPListItem firstItem = itemCollection.First(item => !item.isFolder);
if (firstItem != null)
{
TreeNode firstNode = GetNodeByListItem(my_treeview.Nodes, firstItem, ReportObject);
if (firstNode != null)
{
ReportObject.log("Selecting the first PDF");
selectPDF(my_treeview, firstNode, queryStr_param);
}
}
错误信息:
Sequence contains no matching element
Stacktrace: at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func
2 predicate)
最佳答案
好的,如果没有第一个是异常(exception),
try
{
var first = enumerable.First();
}
catch (InvalidOperationException)
{
// Oops, that was exceptional.
}
如果您预计在某些有效情况下可能没有 first,
var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
// Ok, I need to deal with that.
}
关于c# - 如何在 C# 中处理 List.First 中不匹配的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17472887/