foreach loop
I have two questions
1) my interface i have interface called IRegister and within it i have another interface called IPerson, is that right practice?
2) i have two List(IRegister, IPerson) both can have one or more rows.
what is the best way to loop both List? within GetValidationRules?
public interface IRegister
{
string FirstName { get; }
string MiddleName { get; }
string LastName { get; }
string EmailAddress { get; }
List<IPerson> Student { get; }
}
public static List<ValidationRule> GetValidationRules(List<IRegister> register)
{
List<ValidationRule> validationRules = new List<ValidationRule>();
foreach (IRegister myregister in register)
{
if (string.IsNullOrEmpty(myregister.FirstName))
validationRules.Add(new ValidationRule("Reg", "Must have aFirst Name"));
if (string.IsNullOrEmpty(myregister.LastName))
validationRules.Add(new ValidationRule("Reg", "Must have a Last Name"));
开发者_Go百科 if (string.IsNullOrEmpty(myregister.EmailAddress))
validationRules.Add(new ValidationRule("Reg", "Must have a Email Address"));
IPerson here? how
}
Um, nested loop at your marker.
foreach (IPerson peep in myregister.Student)
{
...
}
While I am not 100% sure what you're trying to accomplish based on your question... I am guessing that you're wondering how to iterate through the Student
propery of IRegister inside the loop...
public interface IRegister
{
string FirstName { get; }
string MiddleName { get; }
string LastName { get; }
string EmailAddress { get; }
List<IPerson> Student { get; }
}
public static List<ValidationRule> GetValidationRules(List<IRegister> register)
{
List<ValidationRule> validationRules = new List<ValidationRule>();
foreach (IRegister myregister in register)
{
if (string.IsNullOrEmpty(myregister.FirstName))
validationRules.Add(new ValidationRule("Reg", "Must have aFirst Name"));
if (string.IsNullOrEmpty(myregister.LastName))
validationRules.Add(new ValidationRule("Reg", "Must have a Last Name"));
if (string.IsNullOrEmpty(myregister.EmailAddress))
validationRules.Add(new ValidationRule("Reg", "Must have a Email Address"));
foreach (IPerson person in myregister.Student)
{
// Not sure what properties you want to check for because
// you didn't show us what the IStudent interface looks like
// so I will just assume that the IStudent object has a
// property for EmailAddress as well
if (string.IsNullOrEmpty(person.EmailAddress))
validationRules.Add(new ValidationRule("Reg", "Student must have a Email Address"));
}
}
}
The easiest way to loop over all of the IPerson
instances is to use SelectMany to flatten the list of IPerson
within the IRegister
instances. For example
foreach ( var person in register.SelectMany(x => x.Student)) {
...
}
This has the effect of creating an IEnumerable<IPerson>
which contains all IPerson
instances from all of the IRegister
values.
精彩评论