将4个列表汇总为1个列表 [英] Aggregate score of four lists to one List

查看:65
本文介绍了将4个列表汇总为1个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Employee个对象的列表.员工班级是这样的:

I have lists of Employee objects. Employee class looks like this:

class Employee
{
   int empId,
   String empName,
   double score,
   String department
}

我有一个这样的字典对象:

I have a dictionary object like this:

Dictionary<int, List<Employee>> = new Dictionary<int, List<Employee>>();

此词典有四个键(1、2、3、4).具有ID的员工可能会出现在所有四个列表中,但可能不会出现.我想要一个汇总的Employee列表,其得分为该员工所有得分的总和.

This dictionary has four keys(1, 2, 3, 4). A employee with a id may be present in all the four lists and may not be present. I want a aggregated list of Employee with score as sum of all the scores for an employee.

示例:如果Id = 1的雇员在四个列表中的得分分别为10、20、30和40,则结果列表中应具有该雇员的得分为100的条目.我该怎么做?

Example: If a employee with Id = 1, has score as 10, 20, 30 and 40 in four Lists, then the resultant List should have a entry for that Employee with score = 100. How can I do this?

推荐答案

使用LinQ:

var yourdict = new Dictionary<int, List<Employee>>();
var yourId = 17;

var score = yourDict.Values
                    .SelectMany(x => x)
                    .Where(emp => emp.empId == yourId)
                    .Select(x => x.score)
                    .Sum();

或为所有分组:

var employeeIdsAndScores = yourDict.Values
                                   .SelectMany(x => x)
                                   .GroupBy(emp => emp.Id)
                                   .Select(g => new { EmployeeId = g.Key, Score = g.Select(x => x.score).Sum() } );

foreach(var emp in employeeIdsAndScores)
{
   Console.WriteLine("Employee Id={0} scored {1} points in total", emp.EmployeeId, emp.Score);
}

这篇关于将4个列表汇总为1个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆