简体   繁体   English

如何获得列表中多于一列的总计并将其使用LINQ放入对象中?

[英]How can I get totals for more than one column in a list and put this into an object using LINQ?

How can I get a total of the count of some columns in a list using LINQ and put this into an object? 如何使用LINQ获取列表中某些列的总数并将其放入对象?

I have a list that 我有一个清单

List<History> a = getTodayData(); 

where my class History looks like this: 我的课程历史记录如下所示:

public class History
{
    public Int32 Id { get; set; }
    public string YYMMDD { get; set; }
    public int Quiz { get; set; }
    public int Views { get; set; }
    public int Clicks { get; set; }
    public int Points { get; set; }
}

What I would like is to populate this object with the totals for each of Views, Clicks and Points. 我想用每个“视图”,“点击”和“点”的总数填充该对象。

public class Today
{
    public int Views { get; set; }
    public int Clicks { get; set; }
    public int Points { get; set; }
}

Some help / advice would be much appreciated. 一些帮助/建议将不胜感激。

With LINQ you can simply calculate the sums separately: 使用LINQ,您可以简单地分别计算总和:

Today today = new Today {
    Views = a.Sum(history => history.Views),
    Clicks = a.Sum(history => history.Clicks),
    Points = a.Sum(history => history.Points),
}

In the most unlikely event you run into performance issues with this solution, you can always use a non-LINQ foreach loop: 在这种解决方案遇到性能问题的极少数情况下,您始终可以使用非LINQ foreach循环:

Today today = new Today();
foreach(History history in a) {
    today.Views += history.Views;
    today.Clicks += history.Clicks;
    today.Points += history.Points;
}

Use this one and let me know if it is work for you or not. 使用此功能,让我知道它是否对您有用。

List<History> a = getTodayData();
 Today t = new Today
           {
            Clicks = a.Sum(h => h.Clicks),
            Views=a.Sum(h=>h.Views),
            Points=a.Sum(h=>h.Points)
        };

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

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