2017-10-08 62 views
0

我有一個C#類的人,我想總的小時數:C#for循環和做加法

 Person Person1 = new Person(); 
     Person1.Name = "Paul"; 
     Person1.Age = 38; 
     Person1.actualGender = Person.Genders.male; 
     Person1.workedHours = 15.5f; 

     Person Person2 = new Person(); 
     Person2.Name = "Frank"; 
     Person2.Age = 15; 
     Person2.actualGender = Person.Genders.female; 
     Person2.workedHours = 5f; 

我能做到這一點是這樣的:

 float TotalHours; 
     TotalHours = Person1.workedHours + Person2.workedHours; 

但如何我是否真的在foreach循環中執行,因爲我必須有2個以上的人。

我的類:

{ 
    public string Name { get; set; } 
    public int Age { get; set; } 
    public enum Genders { male, female } 
    public Genders actualGender { get; set; } 
    public float workedHours { get; set;} 
} 
+2

你應該學習使用數組fore'' –

回答

1

我建議使用列表即:

構建一個列表來保存對象:

List<Person> peopleList = new List<Person>(); 
// call peopleList.add then add your objects 

,那麼你可以在對象和迭代總計他們的workedHours

float totalHours = peopleList.Sum(p => p.workedHours); 

使用foreach循環:

float totalHours = 0; 
foreach(Person p in peopleList){ 
    totalHours += p.workedHours; 
} 
1

您必須添加在列表中的對象和:如果你想

var totalHours = people.Sum(p => p.workedHours); 

如果你想一般的總和,你可以這樣做你可以這樣做:

foreach (var person in people) 
     { 
      var sum = people.Where(p => p.Name.Equals(person.Name)).Sum(p => p.workedHours); 
      Console.WriteLine(sum); 
     } 
+1

此行'var sum = people.Where(p => p.Name.Equals(person.Name))。Sum(p => p.workedHours);'是多餘的,不必要的,會給出錯誤的結果當兩個或更多人擁有相同的名字時。如果你想每個人工作幾小時,爲什麼不在'foreach內部的'Console.WriteLine(person.workedHours)'裏面? –

+0

@Aominè,我只是用例子的名字,正確的是身份字段。如果您單獨展示像您一樣展示的person.workedHours,則在列表中有不止一個同一人 – novac