c# - 如何在 C# 中处理 List.First 中不匹配的情况?

标签 c# .net linq

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, Func2 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/

相关文章:

c# - SQL Server session 上下文限制

c# - Rhino Mock 调用异步任务方法

c# - 告诉 C# 变量具有接口(interface)的属性

c# - 使用Task.WhenAny等待几种不同的异步操作的结果

.NET:向同一应用程序的所有实例发送文本消息并阅读

C# 3.5 合并 2 个不同类型的列表

.net - 如何找到有问题的LINQ to SQL语句?

c# - HttpClient PutAsync 使用 RestAPI 更新字段

c# - LINQ In Clause With Group By 和每个组中的 TOP N 记录

c# - 如何将 OrderBy 表达式数组传递给方法?