使用.net 2.0进行分组是如何做到的
本文关键字:何做 net 使用 | 更新日期: 2023-09-27 18:02:49
正在做。net 2.0项目,没有linq,不能添加任何外部库。
构建一个我在实际项目中需要做的小示例。
如何按例如"员工"进行分组。
对于每一组我都需要做一些事情。
你如何在。net 2.0中分组?
class Program
{
static void Main(string[] args)
{
List<Employee>employees=new List<Employee>();
Employee employee = new Employee();
employee.Id = 1;
employee.Category = "Management";
Employee employee2 = new Employee();
employee.Id = 2;
employee.Category = "Management";
Employee employee3 = new Employee();
employee.Id = 3;
employee.Category = "Director";
Employee employee4 = new Employee();
employee.Id = 4;
employee.Category = "Worker";
Employee employee5= new Employee();
employee.Id = 5;
employee.Category = "Director";
Employee employee6 = new Employee();
employee.Id = 6;
employee.Category = "Worker";
employees.AddRange(new Employee[] { employee, employee2, employee3, employee4, employee5, employee6 });
//1)Group them by category in .net 2.O NO LINQ
//2)Foreach item in the group do something.
Console.WriteLine("??");
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
谢谢你的建议
如何:
Dictionary<string, List<Employee>> groups =
new Dictionary<string, List<Employee>>();
foreach(Employee emp in employees) {
List<Employee> group;
if(!groups.TryGetValue(emp.Category, out group)) {
group = new List<Employee>();
groups.Add(emp.Category, group);
}
group.Add(emp);
}
foreach(KeyValuePair<string,List<Employee>> pair in groups) {
Console.WriteLine(pair.Key);
foreach(Employee emp in pair.Value) {
Console.WriteLine(emp.Id);
}
}
您可以使用Dictionary<TKey,List<TValue>>
。
foreach(var employee in employees)
{
List<Employee> values;
if(!dict.TryGetValue(employee.Category,out values))
{
values=new List<Employee>();
dict.Add(employee.Category,values);
}
values.Add(employee);
}
您可以使用Dictionary<字符串,List>
Dictionary<string, List<Employee>> dict = new Dictionary<string, List<Employee>>();
foreach(Employee e in employees)
{
if(!dict.contains(e.Category))
dict.Add(e.Category, new List<Employee()>);
dict[e.Category].Add(e);
}
试试下面的代码。如果你想更改GroupBy,只需使用不同的GroupFieldDelegate。
public delegate string GroupFieldDelegate(Employee e);
private static string CategoryGrouping(Employee e)
{
return e.Category;
}
static Dictionary<string, List<Employee>> Group(List<Employee> Data, GroupFieldDelegate Grouping)
{
Dictionary<string, List<Employee>> result = new Dictionary<string, List<Employee>>();
foreach (Employee e in Data)
{
string Category = Grouping(e);
if (result.ContainsKey(Category)) result[Category].Add(e);
else (result[Category] = new List<Employee>()).Add(e);c
}
return result;
}