- Home /
Different ending for a foreach loop?
I am looking to do something at the end of a foreach loop, something like this.
List<string> myList = new List<string> {"Connor", "Hudson", "Alex", "Josh"};
string myString = "John";
//Something to detect if myString is not in myList at all, then to add it.
foreach (string name in myList)
{
if( myString == name)
{
//Do nothing
}
//Only do this if it doesnt match any of them
myList.Add(myString);
}
The main purpose of this is to check if the string is already in the list, and if it isnt then add it. Is there another way than a foreach loop? What would be the best way to achieve this?
Answer by Bunny83 · Mar 18, 2021 at 01:33 AM
Your whole logic is flawed at the moment. It makes no sense to have your Add line inside the foreach loop since you do not want to add the item for every element in the list. You just need to check all elements and once you checked all elements ( which means after the foreach loop) you either want to add it or not. The simplest way to implement such behaviour is in a seperate method because you don't need a boolean to track if you found the element or not because you can simply early exit the whole method if you found the element.
void AddIfNotExists(string aNewName)
{
foreach (string name in myList)
{
if(name == aNewName)
return;
}
// we only get here if the passed string is not in the list yet.
myList.Add(aNewName);
}
Though the List class does already have a method to test if a certain element is in the list. So you can simply do:
if (!myList.Contains(myString))
myList.Add(myString);
Thank you so much! I didnt know if there was any way to do this. This worked for me.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
foreach a array inside a generic list 1 Answer
C# ArrayList match to string? 1 Answer
Help with Lists and SelectionGrid 1 Answer