0

我有一堂课:-

Class EmployeesList
{
    public string Category{get;set;}
    public string Name{get;set;}
}

和一个list<EmployeesList>ListOfEmployee-

Category = “AA”  Name= “A”
Category = “AA”  Name= “B”
Category = “AA”  Name= “C”
Category = “AA”  Name= “D”
Category = “BB”  Name= “E”
Category = “BB”  Name= “F”    
Category = “CC”  Name= “G”
Category = “CC”  Name= “H”
Category = “CC”  Name= “I”

我做了两个模型类

Class EmployeeModel
{
    public string EmployeeCategory(get;set;)
    public List<Employees> EmployeeList {get;set;}
}
Class Employee
{
    public string EmployeeName(get;set;)
    public int EmployeeID(get;set;)
}

ObservableCollection<EmployeeModel>我的 问题是如何ListOfEmployee使用 LINQ。

我试过了,但没有得到正确的输出。在这种情况下,EmployeeList 总是有第一个和冗余的值。请帮忙。

var tables = ListOfEmployee
             .GroupBy(f => f. EmployeeCategory)    
             .Select(f => new Employee
                          {
                              EmployeeName = f.Key,
                              EmployeeList 
                                 = f.Select(g => new Employee 
                                                 { EmployeeName = f.First().Name}
                                            )
                                     .ToList()
                            }
                      )
             .ToList();
4

1 回答 1

3

尝试以下操作:

var employees = ListOfEmployee
    .GroupBy(e => e.Category)
    .Select(g =>
        new EmployeeModel()
        {
            EmployeeCategory = g.Key,
            EmployeeList = g.Select(e =>
                new Employee()
                {
                    EmployeeName = e.Name,
                    EmployeeID = GetEmployeeID()
                }).ToList()
        });

return new ObservableCollection<EmployeeModel>(employees);
于 2013-04-24T11:07:53.643 回答