sloan,
Just return, or if you want to go to the code after the loop, use break:
public bool AllDeptIDsMatch(EmpCollection ec)
{
// This assumes you have a count property. If there are
// no items, or one item, they are all the same.
if (ec.Count <= 1)
{
// They are all the same.
return true;
}
// Get the first value.
int id = ec[0].DeptID;
// Cycle through all the employees. If the department id
// is different for any of them, return false.
foreach (Employee e in ec)
{
if (e.DeptID != id)
{
// They are not all the same.
return false;
}
}
// They are the same.
return true;
}
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
(E-Mail Removed)
"sloan" <(E-Mail Removed)> wrote in message
news:ubvt$(E-Mail Removed)...
>
> What is the most concise way to ...... bail out of a loop (or return
> false)
> if one value isn't the same as all the others in a collection?
>
>
> For example:
>
>
> I have an EmpCollection, which is a collection of Employee objects.
> Employee object has a .DeptID property (int)
>
> Let's say I want to verify all DeptID 's are the same for a collection of
> (N
> number) of employees.
>
>
> public bool AllDeptIDsMatch ( EmpCollection ec )
> {
> bool returnValue = false; // or true
>
> for each (Employee e in ec)
> {
>
> Console.WriteLine ( e.DeptID ) ;
> //???/
>
> }
>
>
>
> return returnValue;
>
> }
>
>
> For clarity,
>
> e1.DeptID = 101;
> e2.DeptID = 101;
> e3.DeptID = 101;
> the above would return true
> ..........
> e1.DeptID = 101;
> e2.DeptID = 101;
> e3.DeptID = 101;
> e4.DeptID = 202;
> e5.DeptID = 101;
> e6.DeptID = 101;
> the above would return false.
>
>
>
>
> I've written some code , but seems too verbose.
>
> This is still for 1.1 fyi.
>
>
>
>