Sum()方法计算集合中数字项的总和。
下面的示例演示原始集合上的Sum()方法。
IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 }; var total = intList.Sum(); Console.WriteLine("总计: {0}", total); var sumOfEvenElements = intList.Sum(i => { if(i%2 == 0) return i; return 0; }); Console.WriteLine("偶数元素的总计: {0}", sumOfEvenElements );
总计:243 偶数元素的总计:90
下面的示例计算学生集合中所有学生的年龄总和,以及成年学生的人数。
IList<Student> studentList = new List<Student>>() { new Student() { StudentID = 1, StudentName = "John", Age = 13} , new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} , new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 } }; var sumOfAge = studentList.Sum(s => s.Age); Console.WriteLine("学生年龄总和: {0}", sumOfAge); var numOfAdults = studentList.Sum(s => { if(s.Age >= 18) return 1; else return 0; }); Console.WriteLine("成年学生人数: {0}", numOfAdults);
// 学生集合 Dim studentList = New List(Of Student) From { New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13}, New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21}, New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18}, New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20}, New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15} } Dim sumOfAge = studentList.Sum(Function(s) s.Age) Console.WriteLine("学生年龄总和: {0}", sumOfAge) Dim numOfAdults = studentList.Sum(Function(s) if(s.Age >= 18) return 1 else return 0 end if end function) Console.WriteLine("成年学生人数: {0}", numOfAdults)
学生年龄总和:87 成年学生人数:3
C# 查询语法中不支持Sum运算符。
// 学生集合 Dim studentList = New List(Of Student) From { New Student() With {.StudentID = 1, .StudentName = "John", .Age = 13}, New Student() With {.StudentID = 2, .StudentName = "Moin", .Age = 21}, New Student() With {.StudentID = 3, .StudentName = "Bill", .Age = 18}, New Student() With {.StudentID = 4, .StudentName = "Ram", .Age = 20}, New Student() With {.StudentID = 5, .StudentName = "Ron", .Age = 15} } Dim totalAge = Aggregate st In studentList Into Sum(st.Age) Console.WriteLine("所有年龄段的总和: {0}", totalAge);
所有年龄段的总和:87