如何通过linq获取嵌套对象的值的计数

时间:2013-12-12 08:57:17

标签: c# linq

任何人都可以建议如何使用linq获取所有Event个对象的总和。

new Category
{
     CategoryId = "NUTR",
     CategoryName = "NUTR",
     CategoryDescription = "NUTR Desc",
     TotalPoints = "100",
     Events = new List<Event>
           {
             new Event{Firstname = "HELEN",Surname = "BECKETT", 
                 Points = "10", Description = "NUTR Desc",Eventdate = "2013/04/19",EntityNumber = "1203206956"},
             new Event{Firstname = "PAUL",Surname = "BECKETT", 
                 Points = "90", Description = "NUTR Desc",Eventdate = "2013/06/19",EntityNumber = "1203206957"}
           }
}

2 个答案:

答案 0 :(得分:5)

您需要使用SelectMany来展平events的列表,然后执行总结:

var totalPoints = categories
    .SelectMany(c => c.Events)
    .Sum(e => Convert.ToInt32(e.Points));

答案 1 :(得分:-1)

如果我正确理解了这个问题,可以通过Linq来实现 我建议你尽可能将点的类型从字符串更改为int

Category cat = ....

var countEvents = cat.Sum(i=>i.Events.Sum(ii=>ii.Points));