Iftikhar Ali
Iftikhar Ali

Reputation: 25

Lambda NULL check in List foreach find method

How can I check for NULL value in lambda expression having ForEach and Find methods.

For instance I've a below method which takes a comma separated list of values, iterate through them and for each value finds a SelectListItem which if found is marked as Selected. The issue comes when no matching item is found and it throws null reference exception.

private static void MarkListItemsSelected(string param, IList<SelectListItem> items)
{
    var filters = param.Split(';');
    filters.ToList()
     .ForEach(x => items.ToList()
                   .Find(y => y.Text.ToUpper().Equals(x.ToUpper()))
                   .Selected = true);
}

Upvotes: 0

Views: 3866

Answers (2)

Cory Charlton
Cory Charlton

Reputation: 8938

Just add a null check to lambda:

private static void MarkListItemsSelected(string param, IList<SelectListItem> items)
{
    var filters = param.Split(';');
    filters.ToList().ForEach(
        x =>
        {
            var found = items.ToList().Find(y => y.Text.ToUpper().Equals(x.ToUpper()));
            if (found != null)
                found.Selected = true;
        });
}

Upvotes: 1

B2K
B2K

Reputation: 2611

Linq example:

private static void MarkListItemsSelected(string param, IList<SelectListItem> items)
{
    var filters = param.ToUpper().Split(';');

    items.ToList()
         .ForEach(x => { x.Selected = filters.Contains(x.Text.ToUpper());});
}

Traditional loops:

private static void MarkListItemsSelected(string param, IList<SelectListItem> items)
{
    var filters = param.ToUpper().Split(';');

    foreach( var x in items ) {
        x.Selected = filters.Contains(x.Text.ToUpper());
    }
}

Upvotes: 5

Related Questions