Make Foreach after meeting a condition in List

list.foreach c#
c# foreach array
c# foreach (string array)
how to add values to list in c# using foreach loop
condition in foreach loop c#
c# loop through list of objects
c# foreach continue
list of string foreach

I am creating a static sign in page using List to save the data. I am using a ForEach to loop through the list but the issue I am facing is I want my for loop to stop immediately the condition is true.

NB: I have tried using a break and a return but they are not working as expected.

The code is here:

List<User> users = new List<User>(3);
    public MainWindow()
    {
        InitializeComponent();

        User superAdmin = new User()
        {
            userType = "Super Admin",
            uniqueCode = "123456",
            password = "password1"
        };
        User admin = new User()
        {
            userType = "Admin",
            uniqueCode = "654321",
            password = "password16"
        };
        User userOperator = new User()
        {
            userType = "Operator",
            uniqueCode = "109105",
            password = "specialpassword"
        };

        users.Add(superAdmin);  
        users.Add(admin);
        users.Add(userOperator);
    }



    private void login_OnClick(object sender, RoutedEventArgs e)
    {
        string userType = cmbAdminType.Text;
        string uniqueCode = txtUniqueCode.Text;
        string password = txtPassword.Text;

        foreach (User userPick in users)
        {        
            if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
            {
                MessageBox.Show("Cool you are in!");
                break;
            }
            else
            {
                MessageBox.Show("Err, not found!");
                break;
            }

        }

    }
}
    public class User
    {
        public string userType { get; set; }
        public string uniqueCode { get; set; }
        public string password { get; set; }
    }

Please, what else can I do?

Others have pointed out the flaw in your current code, but I'd suggest using a LINQ approach here. It's much shorter and easier to read - at least when you're used to LINQ:

bool validUser = users.Any(user => user.userType == userType && user.uniqueCode == uniqueCode);
MessageBox.Show(validUser ? "Cool you are in!" : "Err, not found!");

Any is short-circuiting: it stops as soon as it finds a match.

As a side-note, I'd strongly encourage you to start following .NET naming conventions for your properties.

c# - Make Foreach after meeting a condition in List, Others have pointed out the flaw in your current code, but I'd suggest using a LINQ approach here. It's much shorter and easier to read - at least  you mean something like foreach (var item in MyList.Where(condition)) – Kikaimaru Dec 2 '10 at 14:27 2 You realize that whether the boolean evaluation is part of the loop declaration or if it is an if statement that breaks at the beginning of the loop, they are functionally the same, right?

I believe that this could be because you have a logical error in the way that your code is working.

Currently, you break from your foreach loop on the first successful match, or the first unsucessful match. So basically, your enumeration will break after 1 iteration whether successful or not.

You could introduce a flag that you use to record success, or not, and then test this after the enumeration, as so:

private void login_OnClick(object sender, RoutedEventArgs e)
{
    string userType = cmbAdminType.Text;
    string uniqueCode = txtUniqueCode.Text;
    string password = txtPassword.Text;
    bool isMatched = false;

    foreach (User userPick in users)
    {        
        if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
        {
            isMatched = true;
            break;
        }
    }

    if (isMatched)
    {
        MessageBox.Show("Cool you are in!");
    }
    else
    {
        MessageBox.Show("Err, not found!");
    }
}

foreach in list or foreach in list.where, Tell us what you've tried and why it didn't meet your needs. But this is C# and Linq, so now the list will be either an iterator or it will be translated Rather it is an enumerator of lstItem with the Where condition on it. your code, the temporary list variable will get optimised away unless it's used later on. If i use that i should know each position of item i want to add after but when i add an item to list this will resize the list or maybe i've got something wrong. – eugeneK Feb 27 '12 at 9:22 You could just simply use a for loop instead of a foreach loop.

Your loop stops after the first object found in the list. I think what you want to accomplish is that it breaks either when the object you looked for is found either at the end of the loop, if the object you were looking for had not been found. The code:

bool userInside = false;
foreach (User userPick in users)
    {        
        if (userPick.userType == userType && userPick.uniqueCode == uniqueCode)
        {
            MessageBox.Show("Cool you are in!");
            userInside=true;
            break;
        }                
    }
if (userInside==false)
    {
        MessageBox.Show("Err, not found!");
    }

I hope this helps. ^^

Filtering foreach loops with a where condition vs continue guard , If you do need to step into the lambda, then I suggest factoring it out into and so that the iterator of List<T> , which is actually a struct , does not  The node list object does have a forEach method that functions the exact same as the Array forEach method. Which is nice, but just note you are not working against an array, so if you supply an enumration object to a method expecting an array things might blow up on you.

C# foreach statement, Microsoft Build May 19-20, 2020 | Digital event The foreach statement executes a statement or a block of statements for each var fibNumbers = new List<int> { 0, 1, 1, 2, 3, 5, 8, 13 }; int count = 0; foreach (int element in  As the title suggests. How do I do this? I want to call whenAllDone() after the forEach-loop has gone through each element and done some asynchronous processing. [1, 2, 3].forEach( function(it

Use the apply to each action to loop through an array of items , Prerequisites; Create a flow; Add actions and conditions; Run the flow per day) and use a loop action such as Apply to each to process a list of items. Checks each of the 10 messages to confirm if any has meet now in the subject. Select + New step, and then type outlook into the search box to find all  In Python, list's methods clear(), pop(), and remove() are used to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.Remove all items: clear() Remove an item by index and get its value: pop() Remove a

A Comprehensive Walkthrough of C# Iterative Statements Part 2, In this guide, we will focus on another important loop: for / foreach Then I will show you the code templates and flowcharts of iterative The for statement is composed of initializer , condition Implement bool MoveNext() to check whether we can get the next element (return false when reaching the end). A foreach loop runs a block of code for each element of a list. No big whoop, “perl foreach” continues to be one of the most popular on Google searches for the language. No big whoop, “perl foreach” continues to be one of the most popular on Google searches for the language.

Comments
  • What's wrong with break? If you're looking for alternatives you can also return a value to break out.
  • are you sure that the if condition is correct? you may test its value
  • @Adriani6 break will work for the first value and return false for all others
  • @david Yes, the if condition works well for the first test.
  • @heywhydot16 Ah, I see what you did now. I completely missed the point.
  • Thanks a lot. Your recommendation is noted!
  • Thanks, this helped too.