foreach循环

时间:2010-03-17 17:37:58

标签: c# validation

我有两个问题

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
        }

3 个答案:

答案 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"));
        }
    }
}