2013-12-15 84 views
0

我有這樣的類如何從類列表中獲取價值?

class single_request 
{ 
    public int _time_service { get; set; } 
} 

而這樣的名單,我在其中添加了一些這些類的。

List<single_request> list_Srequests = new List<single_request>(); 

最後,我只需要從類,地處list_Srequests總結所有_time_service。我想這樣的代碼,使用SelectMany

foreach (int time_service in list_Srequests.SelectMany(v => v._time_service)) 
{ 
    total_time_SingleReq =+ time_service; 
} 

,但它說,有在第一線的錯誤,像try to identify explicitly。這裏有什麼問題?如果可能的話,提供一個真正的。

+0

'periodic_request'的外觀如何? – Muctadir

+1

@Rocketq - 使用'Select'來代替'SelectMany'。也在答案中更新。 –

回答

2

您可以使用的simpy通過LINQ提供Sum擴展方法 -

total_time_SingleReq = list_Srequests.Sum(v => v._time_service) 

問題在你的代碼 -

你應該在的地方SelectMany使用Select

加法的簡寫操作符不正確。它應該是+=而不是=+。 使用+=會將total_time_SingleReq設置爲上一個循環值time_service

foreach (int time_service in list_Srequests.Select(v => v._time_service)) 
{ 
    total_time_SingleReq += time_service; 
} 
1

使用琛

total_time_SingleReq = list_Srequests.Sum(x=>x._time_service); 
1

你可以做這樣的事情

List<single_request> list_Srequests = new List<single_request>(); 

int totalvalue = 0; 
foreach(single_request aRequest in list_Srequests) 
{ 
    int currentvalue = aRequest._time_service ; 
    totalvalue += currentvalue ; 
} 
+0

謝謝你這樣的回答,因爲我稍後需要它。 – Rocketq

1

最快和簡單的解決方案是使用LINQ Sum

total_time_SingleReq = list_Srequests.Sum(req=>req._time_service); 

爲了更好地理解檢查MSDN Example