0

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Troom
  • 431
  • 6
  • 10
  • 1
    Hi Troom, welcome to SO. Can you re-check your code if it is the exact same code that you shared here is throwing the exception, or you have something like `var productId = productsResponse.Where(...).FirstOrDefault().ProductId` ?? – Arghya C Dec 08 '20 at 18:53

1 Answers1

0

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();
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
  • Thank you very much, I ran out of knowledge about null checking from an external API. I have to read about it, you helped me a lot. – Troom Dec 09 '20 at 11:29