Home > Mobile >  How to add to end of list only if value not found anywhere in for each loop in c#
How to add to end of list only if value not found anywhere in for each loop in c#

Time:08-05

I am iterating through a list of numbers. If the number is not located anywhere in the list I want to add it into the list. I have an issue with my code.

foreach(String id in TestObject.Tags.ToList())
{
    if (id.Equals(x))
    {
        break;
    }
    else
    {
        TestObject.Tags.Add(x.ToString());
    }
}

There is a problem with my code. For example if the "id" didn't equal x then it would add "x" to the list. However "x" maybe located in the list however the foreach has not reached that point yet.

How do I fix this to check the whole list and if the id is not located anywhere in the list then add "x"

CodePudding user response:

You should only add if you finished iterating, not on every iteration.

To do so just introduce a bool-flag that indicates if you found the item already. If you found it, you can imediately break off the loop, otherwise just continue iterating.

bool found = false;
foreach(String id in TestObject.Tags.ToList())
{
    if (id.Equals(x))
    {
        found = true;
        break;
    }
}
if(!found)
    TestObject.Tags.Add(x.ToString());

A shorter approach however is using IEnumerable<T>.Contains:

if(!TestObjects.Tags.Contains(x))
    TestObjects.Tags.Add(x);
  • Related