Willy
Willy

Reputation: 10650

LINQ obtaining first item not empty or null from Dictionary

I have below dictionay:

    Dictionary<string, List<System.ComponentModel.DataAnnotations.ValidationResult>> resp;
    resp = new Dictionary<string, List<System.ComponentModel.DataAnnotations.ValidationResult>>();

And I am trying to obtain the first ErrorMessage from ValidationResult that is not null/empty.

I have create below LINQ expression:

    string msg = resp.First(l => l.Value != null).Value.First(vr => vr != null && !String.IsNullOrEmpty(vr.ErrorMessage)).ErrorMessage;

but it raises an Invalid Operation Exception when all the items in the validationResult list for all keys are null and/or empty. It works well when there is at least one validationresult different from null/empty.

Better an image than thousand words so see shared code here.

Upvotes: 1

Views: 1712

Answers (1)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43916

First() throws this exception when there is no matching element in the dictionary. It seems you are looking for FirstOrDefault() which returns null instead of throwing.

Btw: Your algorithm has a little flaw: If there is a non-null list but it only contains ErrorMessages of null you don't check the next non-null list.

I suggest to query like that:

string msg = resp.Where(x => x.Value != null)
                 .SelectMany(x => x.Value.Select(vr => vr?.ErrorMessage))
                 .FirstOrDefault(m => !string.IsNullOrEmpty(m));

Upvotes: 3

Related Questions