如何使用LINQ获取列表中某些列的总数并将其放入对象?
我有一个列表
List<History> a = getTodayData();
我的课程历史记录如下:
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; }
}
我想用每个“视图”,“点击”和“点”的总数填充该对象。
public class Today
{
public int Views { get; set; }
public int Clicks { get; set; }
public int Points { get; set; }
}
一些帮助/建议将不胜感激。
答案 0 :(得分:5)
使用LINQ,您可以简单地分别计算总和:
Today today = new Today {
Views = a.Sum(history => history.Views),
Clicks = a.Sum(history => history.Clicks),
Points = a.Sum(history => history.Points),
}
在这种解决方案遇到性能问题的极少数情况下,您始终可以使用非LINQ foreach
循环:
Today today = new Today();
foreach(History history in a) {
today.Views += history.Views;
today.Clicks += history.Clicks;
today.Points += history.Points;
}
答案 1 :(得分:1)
使用这个,让我知道它是否对您有用。
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)
};