如何从课程列表中获取价值?

时间:2013-12-15 10:20:22

标签: c# list

我有这样的课程

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。这有什么不对?如果可能的话,提供真实的。

3 个答案:

答案 0 :(得分:2)

您可以简单地使用LINQ提供的Sum扩展方法 -

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

代码中存在问题 -

您应该使用Select代替SelectMany

添加的速记运算符也不正确。它应该是+=而不是=+。 使用+=会将total_time_SingleReq设置为上次循环值time_service

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

答案 1 :(得分:1)

使用Sum

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

答案 2 :(得分:1)

最快捷的解决方案是使用LINQ Sum

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

为了更好地理解,请检查MSDN Example