Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading