if condition in foreach loop
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: if condition in foreach loop

  1. #1
    Join Date
    May 2012
    Posts
    8

    if condition in foreach loop

    Hi all,

    I have something like this in my code..

    I have a Students list.

    foreach(var name in Students)
    {
    if(name.StudentName == "John")
    {
    //Do Something
    }
    else(name.StudentName == "ALEX")
    {
    //Do Something
    }
    }

    Is there any better approach for this?

    Thanks,
    Genith

  2. #2
    Join Date
    Jan 2010
    Posts
    1,099

    Re: if condition in foreach loop

    Well, can you generalize the "//Do something" part so that it can be parametrized and then applied to all the students in the same way? Is there a common pattern you can use? If there is, you can write one or more methods and use the properties associated with the student objects, and possibly some other values, as parameters to a common algorithm.

  3. #3
    Join Date
    May 2012
    Posts
    8

    Re: if condition in foreach loop

    Thanks for the reply. There is no common pattern. In //Do something i need to turn on some Boolean properties. I looking for something in place of foreach loop.

    Thanks

  4. #4
    Join Date
    Jul 2012
    Posts
    90

    Re: if condition in foreach loop

    Assuming you actually wanted to replace the if construct (instead of the foreach as stated in your reply to TGC - foreach is the best way to iterate through a List)...

    Code:
        foreach (var name in Students) {
            switch (name.StudentName.ToLower()) {
                case "john":
                    // Do something specific to John
                    break;
                case "alex":
                    // Do something specific to Alex
                    break;
                case "james":
                case "robert":
                    // Do something specific to both James and Robert
                    break;
                default:
                    // Do something if not John, Alex, James, or Robert
                    break;
            }
            // If you need - you can do something here common to all
        }
    Last edited by CGKevin; October 12th, 2012 at 08:17 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center