locked
check string in for loop...null RRS feed

  • Question

  • User-507786106 posted

    How do I check the string in a for loop to see if it is null or not.

    Example:

    foreach (var item in validateList.ToString())

    {

       how do I check to see if item list is not null

       if it is not null add to newList.Add(Item)  --- only if not null

    }

    Monday, July 21, 2014 11:52 AM

Answers

  • User-1657171777 posted
    foreach (var item in validateList)
    {
      if (item != null)
      {
        newList.Add(item);
      }
    }

    That's the basics of checking for null.  You could also check if a string was empty by using the WhiteSpace check

    if (!string.IsNullOrWhiteSpace(item))
    {
      newList.Add(item);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 11:57 AM

All replies

  • User-1657171777 posted
    foreach (var item in validateList)
    {
      if (item != null)
      {
        newList.Add(item);
      }
    }

    That's the basics of checking for null.  You could also check if a string was empty by using the WhiteSpace check

    if (!string.IsNullOrWhiteSpace(item))
    {
      newList.Add(item);
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 21, 2014 11:57 AM
  • User753101303 posted

    Hi,

    More likely the problem is that you are using var item in validateList.ToString() so more likely you iterate on each character of the type name of validateList.

    Try :

    foreach(var item in validateList)

    The test itsef would be if (item!=null) or perhaps if(!String.IsNullOrEmpty(item)) depending on what you really want (ie only null or null or empty string).

    When showing some code it's always best to tell exactly what is the behavior you see (here it seems the question you ask is not about the problem you really have if you tried somethjing and it didn't work more likely this is because item is a character rather than a strring).

    Monday, July 21, 2014 11:59 AM