简体   繁体   English

如何使用linq对网格中的列中的所有单元格求和

[英]How to perform sum of all cells in a column in grid using linq

I have a requirement. 我有一个要求。 like.... 喜欢....

Sname Marks Percentage

aa    50     50
aa    60     60
bb    80     80
bb    60     60

here i want to add marks and display percentage like below 在这里我想添加标记并显示如下所示的百分比

Sname Marks Percentage
aa    50     50
aa    60     60
-----------------
aa    110    55
----------------
bb    80     80
bb    60     60
-----------------
bb    140    70
-----------------

It should be done using the linq query I am using the follwing linq query which performs grouping for display. 应该使用linq查询来完成。我正在使用下面的linq查询,该查询执行分组以进行显示。

List<Studentsmarkslist> mrksbrpby = (from n in lstmrks
     group n by new { n.StudentName,n.Total,n.Percentage }  
        into g  orderby g.Key.StudentName
     select new Studentsmarkslist
     {
         StudentName = g.Key.StudentName,
         Total = g.Key.Total,
         Percentage = g.Key.Percentage

    }).ToList();
return mrksbrpby

Please suggest me how to perform sum and percentage as mentioned above way using this linq query 请建议我如何使用此linq查询执行上述方法的总和和百分比

you want to use the .Sum() method for summing all the Marks values, and .Average() for getting the average percentage. 您想使用.Sum()方法对所有Marks值求和,并使用.Average()获得平均百分比。

Examples of usage can be found by following the MSDN links: 可以通过以下MSDN链接找到用法示例:

.Sum() read more here: http://msdn.microsoft.com/en-us/library/bb338442.aspx .Sum()在此处了解更多信息: http : //msdn.microsoft.com/zh-cn/library/bb338442.aspx

.Average() read more here: http://msdn.microsoft.com/en-us/library/bb338413.aspx .Average()在此处了解更多信息: http : //msdn.microsoft.com/zh-cn/library/bb338413.aspx

You can group the list of entries by the students' name. 您可以按学生姓名对条目列表进行分组。 Then iterate through each group to display: 然后遍历每个组以显示:

  • Individual entry belong to the student 个人参赛属于学生
  • Aggregated result by LINQ's Sum() and Average() LINQ的Sum()和Average()的合计结果

Like this: 像这样:

var groups = from n in lstmrks
             group n by n.StudentName;
foreach (var g in groups)
{
    foreach (var s in g)
        Console.WriteLine("{0}\t{1}\t{2}", s.StudentName, s.Total, s.Percentage);
    Console.WriteLine("-----------------");
    Console.WriteLine("{0}\t{1}\t{2}", g.Key, g.Sum(x => x.Total), g.Average(x => x.Percentage));
    Console.WriteLine("-----------------");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM