查找自定义类型的列表中最大计数 [英] Find max count of a list of custom types
问题描述
我有一个模拟的应用程序,其中一个继承链像员工,经理,president
等。
I have a mock application where an inheritance chain like
Employee,Manager,President
etc.
Employee类看起来像
The Employee class looks like
class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime HireDate { get; set; }
public Employee()
{
}
}
和Manager类看起来像
and the Manager class looks like
class Manager : Employee
{
private List<Employee> employeesManaged = new List<Employee>();
public List<Employee> EmployeesManaged
{
get { return employeesManaged; }
set { employeesManaged = value; }
}
}
我想编写发现谁管理的大部分员工(其EmployeesManaged.Count财产是最大的)管理者的方法。我现在有两个问题。
I would like to write a method that finds the manager who manages the most employees (whose EmployeesManaged.Count property is the largest). I have two problems currently.
-
你将在code见下面我给每个经理手动添加到列表变量。这不是一个长期的解决方案。什么是解决这一有效,简洁的方式?
as you'll see in the code below I have to manually add each Manager to a List variable. This isn't a long-term solution. What would be an effective, concise manner of solving this?
我的LINQ语法不正确。
my Linq syntax is incorrect.
我想第一个问题是最pressing。如果有1000个Employee对象,我怎么会绕过每增加一个列表?
I think the first problem is most pressing. If there were 1000 Employee objects, how would I circumvent adding each one to a list?
public static Manager GetBestManager(List<Manager> managerList)
{
Manager m = managerList.Select(x => x.EmployeesManaged).Max();
}
我的主要方法
Employee e = new Employee();
e.EmployeeId = 101;
e.FirstName = "Tom";
e.LastName = "Jones";
e.HireDate = DateTime.Now.Subtract(TimeSpan.FromDays(40));
Employee e2 = new Employee();
e2.EmployeeId = 102;
Employee e3 = new Employee();
e3.EmployeeId = 103;
Manager m = new Manager();
m.EmployeeId = 201;
m.EmployeesManaged.Add(e);
m.EmployeesManaged.Add(e2);
Manager m2 = new Manager();
m2.EmployeesManaged.Add(e3);
List<Manager> mList = new List<Manager>();
mList.Add(m);
mList.Add(m2);
Manager.GetBestManager(mList);
与当前的语法我得到的错误无法Employee类型隐式转换为经理
with the current syntax I get the error 'Cannot implicitly convert type Employee to Manager
推荐答案
1),这取决于在数据的来源。一个数据库,从磁盘文件,内存中的集合。通常情况下,列表
或任何结构是由源决定。
1) It depends on where the data is coming from. A database, file from disk, in memory collection. Often the List
or whatever structure is determined by the source.
2)您的LINQ是获得最大数量,而不是管理
最高计数。尝试:
2) Your LINQ is getting the max number, not the Manager
with the highest count. Try:
public static Manager GetBestManager(List<Manager> managerList)
{
Manager m = managerList.OrderByDescending(x => x.EmployeesManaged.Count).First();
return m;
}
这篇关于查找自定义类型的列表中最大计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!