Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle no matches case in List.First in c#?

Tags:

c#

.net

linq

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)

like image 578
omega Avatar asked Jul 04 '13 14:07

omega


3 Answers

Ok, If it is exceptional for there to be no first,

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

If you anticipate that there may be no first in some valid situations,

var first = enumerable.FirstOrDefault();
if (first == default(someType)) // null for reference types.
{
    // Ok, I need to deal with that.
}
like image 172
Jodrell Avatar answered Nov 05 '22 09:11

Jodrell


While you do a null check on the find, you don't in your predicate. The line

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

Might throw an exception it item is null (have you inserted an null item in the collection?) or item.item is null (are you sure it's always there?).

You could do:

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

More chatty, but you won't get a NullReferenceException.

Edit Well you changed your question. Now you do First. The First method will throw an exception if nothing is found. Use FirstOrDefault instead which will return null for a class or the default value for a struct.

    foundItem = itemCollection.FirstOrDefault(item => item != null &&
                                              item.item != null && 
                                              item.item.ID == PDFID);
like image 7
Simon Belanger Avatar answered Nov 05 '22 09:11

Simon Belanger


Replace First by FirstOrDefault :

MySPListItem firstItem = itemCollection.FirstOrDefault(item => !item.isFolder);
like image 3
Larry Avatar answered Nov 05 '22 09:11

Larry