8

In IEnumerable.First function, how do I handle the case if there are no matches? Currently it just crashes...

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

Error Message:

Sequence contains no matching element
Stacktrace: at System.Linq.Enumerable.First[TSource](IEnumerable1 source, Func2 predicate)

4

6 回答 6

22

好吧,如果没有第一是例外,

try
{
    var first = enumerable.First();
}
catch (InvalidOperationException)
{
    // Oops, that was exceptional.
}

如果您预计在某些有效情况下可能没有第一个,

var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
    // Ok, I need to deal with that.
}
于 2013-07-04T15:31:48.763 回答
7

当您null对查找进行检查时,您并没有在您的谓词中。线

    foundItem = itemCollection.Find(item => item.item.ID == PDFID);

可能会抛出异常(您item是否在集合中null插入了一个项目?)或者是(您确定它总是存在吗?)。nullitem.itemnull

你可以这样做:

foundItem = itemCollection.Find(item => item != null &&
                                        item.item != null && 
                                        item.item.ID == PDFID);

更健谈,但你不会得到NullReferenceException.

编辑好吧,你改变了你的问题。现在你做First。如果没有找到,该First方法抛出异常。改用FirstOrDefaultwhich 将返回null一个类或 a 的默认值struct

    foundItem = itemCollection.FirstOrDefault(item => item != null &&
                                              item.item != null && 
                                              item.item.ID == PDFID);
于 2013-07-04T14:54:08.400 回答
3

将 First 替换为FirstOrDefault

MySPListItem firstItem = itemCollection.FirstOrDefault(item => !item.isFolder);
于 2013-07-04T15:00:18.430 回答
2

引用自您链接到的MSDN 网站:

与指定谓词定义的条件匹配的第一个元素(如果找到);否则,类型 T 的默认值。

这描述了返回值。因此,当找不到匹配项时,返回defaulttype 的值T,这意味着null引用类型以及诸如0, false& co 之类的东西。对于值类型。

因此,在您的调用代码中,只需检查此默认值,就可以了:-)。您不能做的只是使用返回的值,因为NullReferenceException如果您使用的是引用类型,这可能会导致 a 。

于 2013-07-04T14:34:19.897 回答
0

It shouldn't throw an exception, you need to handle the case where it returns default(T). You might be getting a NullReferenceException because you're not handling the case where it returns null. For example:

IEnumerable<Cars> cars = GetCars();
Car car = cars.Find(c => c.Model == "Astra");
if(car != null) 
{
   // You found a car!
}

If you were doing the same for a struct, you'd check for it's default instead. Ints for example would be a 0:

int[] ints = new int[] { 1, 4, 7 };
int myInt = ints.Find(i => i > 5);
if(myInt != 0) // 0 is default(int)
{
   // You found a number
}
于 2013-07-04T14:35:25.033 回答
0

检查结果是否为null

   if (result == null)
   {
      Console.WriteLine("Not found");
   }

有一个明确的示例演示如果在此处找到/未找到该项目该怎么办

于 2013-07-04T14:34:50.353 回答