How to check for any null values within a list before processing further?










2















I'm passing a list to a method that operates on the list. However first I want to iterate over the list and check whether or not there are any null values within the list before any further processing takes place.



Initally I thought using the IEnumerable.All() method would help with this, however this method actually checks that all elements of the list satisfy a condition, I'd like to check each element in turn and if any are null then handle this.



This is the (non-working) code that I have already. I'm not sure how I would adapt this for use within an if statement condition.



if (questions == null || questions.Any() == false || questions.All(q => q == null))

throw new ArgumentException("Exception raised.");



Essentially I want to check:



  1. Questions isn't null.

  2. Questions isn't empty.

  3. Any elements held within questions aren't null values.

The first two have been done, it's just the third.










share|improve this question



















  • 2





    Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

    – Grzesiek Danowski
    Nov 14 '18 at 12:47















2















I'm passing a list to a method that operates on the list. However first I want to iterate over the list and check whether or not there are any null values within the list before any further processing takes place.



Initally I thought using the IEnumerable.All() method would help with this, however this method actually checks that all elements of the list satisfy a condition, I'd like to check each element in turn and if any are null then handle this.



This is the (non-working) code that I have already. I'm not sure how I would adapt this for use within an if statement condition.



if (questions == null || questions.Any() == false || questions.All(q => q == null))

throw new ArgumentException("Exception raised.");



Essentially I want to check:



  1. Questions isn't null.

  2. Questions isn't empty.

  3. Any elements held within questions aren't null values.

The first two have been done, it's just the third.










share|improve this question



















  • 2





    Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

    – Grzesiek Danowski
    Nov 14 '18 at 12:47













2












2








2








I'm passing a list to a method that operates on the list. However first I want to iterate over the list and check whether or not there are any null values within the list before any further processing takes place.



Initally I thought using the IEnumerable.All() method would help with this, however this method actually checks that all elements of the list satisfy a condition, I'd like to check each element in turn and if any are null then handle this.



This is the (non-working) code that I have already. I'm not sure how I would adapt this for use within an if statement condition.



if (questions == null || questions.Any() == false || questions.All(q => q == null))

throw new ArgumentException("Exception raised.");



Essentially I want to check:



  1. Questions isn't null.

  2. Questions isn't empty.

  3. Any elements held within questions aren't null values.

The first two have been done, it's just the third.










share|improve this question
















I'm passing a list to a method that operates on the list. However first I want to iterate over the list and check whether or not there are any null values within the list before any further processing takes place.



Initally I thought using the IEnumerable.All() method would help with this, however this method actually checks that all elements of the list satisfy a condition, I'd like to check each element in turn and if any are null then handle this.



This is the (non-working) code that I have already. I'm not sure how I would adapt this for use within an if statement condition.



if (questions == null || questions.Any() == false || questions.All(q => q == null))

throw new ArgumentException("Exception raised.");



Essentially I want to check:



  1. Questions isn't null.

  2. Questions isn't empty.

  3. Any elements held within questions aren't null values.

The first two have been done, it's just the third.







c#






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 13:05









Dmitry Bychenko

107k1093133




107k1093133










asked Nov 14 '18 at 12:44









Jake12342134Jake12342134

1058




1058







  • 2





    Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

    – Grzesiek Danowski
    Nov 14 '18 at 12:47












  • 2





    Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

    – Grzesiek Danowski
    Nov 14 '18 at 12:47







2




2





Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

– Grzesiek Danowski
Nov 14 '18 at 12:47





Hmm, isn't it relevant: questions == null || questions.Any(q => q == null)) ?

– Grzesiek Danowski
Nov 14 '18 at 12:47












3 Answers
3






active

oldest

votes


















5














You can use this more concise version that uses Any and the ?-operator:



bool valid = questions?.Any(q => q != null) == true;
if (!valid)
throw new ArgumentException("Exception raised.");


The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.






share|improve this answer

























  • instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

    – Default
    Nov 14 '18 at 13:31






  • 1





    @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

    – Rango
    Nov 14 '18 at 13:42



















2














I think you want to



if (questions != null && questions.Any() && questions.All(q => q != null))





share|improve this answer
































    1














    I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:



    if (null == questions)
    throw new ArgumentNullException(nameof(questions));
    else if (questions.All(q => q == null))
    throw new ArgumentException("At least one not null question expected.",
    nameof(questions));


    Or even into three: when implementing a contract, in your case it is





    1. questions isn't null.


    2. questions isn't empty.

    3. Any elements held within questions aren't null values.



    try throw separate exception for each violation:



     if (null == questions)
    throw new ArgumentNullException(nameof(questions));
    else if (!questions.Any())
    throw new ArgumentException("Questions must not be empty.",
    nameof(questions));
    else if (questions.Any(item => null == item))
    throw new ArgumentException("Null questions are not allowed.",
    nameof(questions));


    Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).






    share|improve this answer
























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53300555%2fhow-to-check-for-any-null-values-within-a-list-before-processing-further%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      5














      You can use this more concise version that uses Any and the ?-operator:



      bool valid = questions?.Any(q => q != null) == true;
      if (!valid)
      throw new ArgumentException("Exception raised.");


      The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.






      share|improve this answer

























      • instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

        – Default
        Nov 14 '18 at 13:31






      • 1





        @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

        – Rango
        Nov 14 '18 at 13:42
















      5














      You can use this more concise version that uses Any and the ?-operator:



      bool valid = questions?.Any(q => q != null) == true;
      if (!valid)
      throw new ArgumentException("Exception raised.");


      The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.






      share|improve this answer

























      • instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

        – Default
        Nov 14 '18 at 13:31






      • 1





        @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

        – Rango
        Nov 14 '18 at 13:42














      5












      5








      5







      You can use this more concise version that uses Any and the ?-operator:



      bool valid = questions?.Any(q => q != null) == true;
      if (!valid)
      throw new ArgumentException("Exception raised.");


      The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.






      share|improve this answer















      You can use this more concise version that uses Any and the ?-operator:



      bool valid = questions?.Any(q => q != null) == true;
      if (!valid)
      throw new ArgumentException("Exception raised.");


      The comparison with true is necessary to convert the bool? to bool. It also might be more efficient because it doesn't need to execute it multiple times(in case questions is a query). It also handles the case that questions is empty, then Any returns false.







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 14 '18 at 13:02

























      answered Nov 14 '18 at 12:56









      RangoRango

      363k46460721




      363k46460721












      • instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

        – Default
        Nov 14 '18 at 13:31






      • 1





        @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

        – Rango
        Nov 14 '18 at 13:42


















      • instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

        – Default
        Nov 14 '18 at 13:31






      • 1





        @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

        – Rango
        Nov 14 '18 at 13:42

















      instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

      – Default
      Nov 14 '18 at 13:31





      instead of == true, wouldn't it be more correct to use ?? true? i.e. "if I expect the result to be null I want the returned value to be true" instead of "If I expect the result to be null I want it converted to a boolean to compare with true"

      – Default
      Nov 14 '18 at 13:31




      1




      1





      @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

      – Rango
      Nov 14 '18 at 13:42






      @Default: Instead of == true you could also use ?? false. It's a matter of taste what you prefer. I find the == comparison more readable.

      – Rango
      Nov 14 '18 at 13:42














      2














      I think you want to



      if (questions != null && questions.Any() && questions.All(q => q != null))





      share|improve this answer





























        2














        I think you want to



        if (questions != null && questions.Any() && questions.All(q => q != null))





        share|improve this answer



























          2












          2








          2







          I think you want to



          if (questions != null && questions.Any() && questions.All(q => q != null))





          share|improve this answer















          I think you want to



          if (questions != null && questions.Any() && questions.All(q => q != null))






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 14 '18 at 12:54

























          answered Nov 14 '18 at 12:46









          D-ShihD-Shih

          25.8k61531




          25.8k61531





















              1














              I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:



              if (null == questions)
              throw new ArgumentNullException(nameof(questions));
              else if (questions.All(q => q == null))
              throw new ArgumentException("At least one not null question expected.",
              nameof(questions));


              Or even into three: when implementing a contract, in your case it is





              1. questions isn't null.


              2. questions isn't empty.

              3. Any elements held within questions aren't null values.



              try throw separate exception for each violation:



               if (null == questions)
              throw new ArgumentNullException(nameof(questions));
              else if (!questions.Any())
              throw new ArgumentException("Questions must not be empty.",
              nameof(questions));
              else if (questions.Any(item => null == item))
              throw new ArgumentException("Null questions are not allowed.",
              nameof(questions));


              Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).






              share|improve this answer





























                1














                I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:



                if (null == questions)
                throw new ArgumentNullException(nameof(questions));
                else if (questions.All(q => q == null))
                throw new ArgumentException("At least one not null question expected.",
                nameof(questions));


                Or even into three: when implementing a contract, in your case it is





                1. questions isn't null.


                2. questions isn't empty.

                3. Any elements held within questions aren't null values.



                try throw separate exception for each violation:



                 if (null == questions)
                throw new ArgumentNullException(nameof(questions));
                else if (!questions.Any())
                throw new ArgumentException("Questions must not be empty.",
                nameof(questions));
                else if (questions.Any(item => null == item))
                throw new ArgumentException("Null questions are not allowed.",
                nameof(questions));


                Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).






                share|improve this answer



























                  1












                  1








                  1







                  I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:



                  if (null == questions)
                  throw new ArgumentNullException(nameof(questions));
                  else if (questions.All(q => q == null))
                  throw new ArgumentException("At least one not null question expected.",
                  nameof(questions));


                  Or even into three: when implementing a contract, in your case it is





                  1. questions isn't null.


                  2. questions isn't empty.

                  3. Any elements held within questions aren't null values.



                  try throw separate exception for each violation:



                   if (null == questions)
                  throw new ArgumentNullException(nameof(questions));
                  else if (!questions.Any())
                  throw new ArgumentException("Questions must not be empty.",
                  nameof(questions));
                  else if (questions.Any(item => null == item))
                  throw new ArgumentException("Null questions are not allowed.",
                  nameof(questions));


                  Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).






                  share|improve this answer















                  I suggest spliting in two tests - for questions itself (it must not be null) and for items within questions (there must be at least one not null item); your current code changed:



                  if (null == questions)
                  throw new ArgumentNullException(nameof(questions));
                  else if (questions.All(q => q == null))
                  throw new ArgumentException("At least one not null question expected.",
                  nameof(questions));


                  Or even into three: when implementing a contract, in your case it is





                  1. questions isn't null.


                  2. questions isn't empty.

                  3. Any elements held within questions aren't null values.



                  try throw separate exception for each violation:



                   if (null == questions)
                  throw new ArgumentNullException(nameof(questions));
                  else if (!questions.Any())
                  throw new ArgumentException("Questions must not be empty.",
                  nameof(questions));
                  else if (questions.Any(item => null == item))
                  throw new ArgumentException("Null questions are not allowed.",
                  nameof(questions));


                  Such kind implementation may appear wordy but it saves time when you are debugging ("Exception raised." provides no info when meaning of "Questions must not be empty." is evident).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 14 '18 at 13:19

























                  answered Nov 14 '18 at 12:58









                  Dmitry BychenkoDmitry Bychenko

                  107k1093133




                  107k1093133



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53300555%2fhow-to-check-for-any-null-values-within-a-list-before-processing-further%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Top Tejano songwriter Luis Silva dead of heart attack at 64

                      政党

                      天津地下鉄3号線