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
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.
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
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
}