FirstOrDefault throws ArgumentnullException

237 Views Asked by At

My goal is to extract a specific record that has a parameter value specified by me. The data is taken from an external API.

My query looks like this:

var productId = productsResponse.Where(x => x.Parameters.Any(y => y.Values.Any(z => z.Equals(auctionTitle)))).FirstOrDefault();

And it works fine until where filters out all the records. Then the method aborts and debugging cannot continue.

The problem is:

System.ArgumentNullException: Value cannot be null

because source transferred to FirstOrDefault is null.

I also tried:

var productId = productsResponse.Where(x => x.Parameters.Any(y => y.Values.Any(z => z.Equals(auctionTitle)))).DefaultIfEmpty().First();

Please let me know what topic I should read because I have run out of ideas. I really care to understand where I am wrong.

1

There are 1 best solutions below

1
On

This can be not an answer but try this construction:

var productId = productsResponse
   .Where(x => x.Parameters.SelectMany(y => y.Values)
      .Any(z => z == auctionTitle))
   .FirstOrDefault();

Also if data came from external API, it may be needed more null check.

var productId = productsResponse
   .Where(x => x.Parameters?.SelectMany(y => y.Values ?? Enumerable.Empty<Value>())
      ?.Any(z => z == auctionTitle) == true)
   .FirstOrDefault();