2010-03-17 153 views
1

我有兩個問題foreach循環

1)我的界面我有接口稱爲IRegister,在它內部我有另一個接口稱爲IPerson,這是正確的做法?

2)我有兩個列表(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

我猜你正在談論C#,但它會很好,如果你指定的。 – FrustratedWithFormsDesigner 2010-03-17 17:40:54

+0

plz改述你的問題。我不認爲很多人會得到這 – Midhat 2010-03-17 17:41:10

+0

努力理解 - 你有一個註冊,如果註冊是有效的,你想創建一個人? – 2010-03-17 17:44:14

回答

1

雖然我不是100%肯定,你要完成基於你的問題......我猜測你想知道如何通過循環內的Student屬性格式IRegister的迭代什麼...

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")); 
     } 
    } 
} 
+0

謝謝Jessegavin – 2010-03-17 17:55:46

1

遍歷所有IPerson實例的最簡單的方法是使用的SelectMany拼合IRegister情境中的IPerson列表。例如

foreach (var person in register.SelectMany(x => x.Student)) { 
    ... 
} 

這具有創建IEnumerable<IPerson>它包含來自所有IRegister值的所有實例IPerson的效果。

2

恩,嵌套循環在你的標記。

foreach (IPerson peep in myregister.Student) { ... }

+0

謝謝保羅.... – 2010-03-17 17:52:50