如何使用C#汇总重复记录和总和值 [英] How to aggregate duplicate records and sum value using C#
问题描述
我想创建一个列表,其中包含多个业务代表以及他们进行的呼叫数量,如下所示:
I want to create a list where it holds several agents and the number of calls they make and did it like so:
public class Agent
{
public string Agent_ID{ get; set; }
public string Name { get; set; }
public int Calls { get; set; }
}
var list = new List<Agent>() // To create a list to hold the data
{
new Agent() { Agent_ID = "TK_J", Name = "James", Calls = 10 },
new Agent() { Agent_ID = "TK_K", Name = "Kurtis", Calls = 10 },
new Agent() { Agent_ID = "TK_R", Name = "Rebecca", Calls = 5 },
new Agent() { Agent_ID = "TK_J", Name = "James", Calls = 10 },
new Agent() { Agent_ID = "TK_R", Name = "Rebecca", Calls = 5 },
new Agents(){ Agent_ID = "TK_B", Name = "Bobby", Calls = 10 },
};
如您所见,会有多余的数据行.因此,我想使用C#聚合功能(例如分组依据)来汇总相似代理的呼叫次数.我正在尝试的是:
As you can see there will be redundant lines of data. So I want to use C# aggregation function such as group by to sum up the similar agent's number of calls. What I was trying was:
list.GroupBy(i => i.Agent_ID).Select(g => new
{
Agent_ID= g.Key,
Name = */ How do i bring the name here*/,
Calls = g.Sum(i => i.Calls)});
有人可以帮助我吗?感谢任何帮助或建议.如果出现问题,请教我如何修复代码.非常感谢!
Anyone can help me? Appreciate any help or advice. If there is something wrong teach me how to fix the code. Many thanks!!
推荐答案
您当前仅按AgentID进行分组.
您需要将所需的字段投影为一个匿名对象,以便它们可以作为IGrouping<annonymous,Agent>
可供选择.
见下文.
You are currently grouping by only AgentID.
You'll need to project the fields you require as an anonymous object so they can be available as an IGrouping<annonymous,Agent>
to the select.
See below.
list.GroupBy(i => new {i.Agent_ID, i.Name}).Select(g => new
{
Agent_ID= g.Key.Agent_ID,
Name = g.Key.Name,
Calls = g.Sum(i => i.Calls)
});
这篇关于如何使用C#汇总重复记录和总和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!