我有两个问题
1)我的界面我有一个名为IRegister的界面,在其中我有另一个名为IPerson的界面,这是正确的练习吗?
2)我有两个List(IRegister,IPerson)都可以有一行或多行。
循环两个List的最佳方法是什么?在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"));
if (string.IsNullOrEmpty(myregister.EmailAddress))
validationRules.Add(new ValidationRule("Reg", "Must have a Email Address"));
IPerson here? how
}
答案 0 :(得分:2)
嗯,你标记处的嵌套循环。
foreach (IPerson peep in myregister.Student)
{
...
}
答案 1 :(得分:1)
循环所有IPerson
个实例的最简单方法是使用SelectMany在IPerson
个实例中展平IRegister
列表。例如
foreach ( var person in register.SelectMany(x => x.Student)) {
...
}
这样可以创建IEnumerable<IPerson>
,其中包含所有IPerson
值中的所有IRegister
个实例。
答案 2 :(得分:1)
虽然我不能100%确定你想要根据你的问题完成什么...我猜你在想如何在循环中迭代IRegister的Student
属性。
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"));
}
}
}