-
October 11th, 2012, 06:28 PM
#1
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
-
October 11th, 2012, 07:32 PM
#2
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.
-
October 11th, 2012, 07:50 PM
#3
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
-
October 12th, 2012, 07:49 AM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|