我有一个类结构和数据如下:
public class Company
{
public string CompanyName { get; set; }
public List<Employee> Employees { get; set; }
}
public class Employee
{
public string EmployeeName { get; set; }
}
ObservableCollection<Company> list1 = new ObservableCollection<Company>
{ new Company { CompanyName = "com1",
Employees = new List<Employee>
{ new Employee {EmployeeName = "Ron"},
new Employee { EmployeeName = "John" },
new Employee { EmployeeName = "David" } } },
new Company { CompanyName = "com2",
Employees = new List<Employee>
{ new Employee {EmployeeName = "manuel"},
new Employee { EmployeeName = "smith" },
new Employee { EmployeeName = "rony" } } },
new Company { CompanyName = "com3",
Employees = new List<Employee>
{ new Employee {EmployeeName = "kevin"},
new Employee { EmployeeName = "chacko" },
new Employee { EmployeeName = "willy" } } }};
我想根据公司类中的外部公司名称对Employee类中的employeesenames进行分组。我怎样才能在linq中实现这一目标。
答案 0 :(得分:1)
我得到了它的工作, 我添加了一个继承IEnumerable
的类 class GroupViewModel<T> : IEnumerable<T>
{
public IEnumerable<T> Items { get; private set; }
public string Name { get; private set; }
public string Id { get; private set; }
public GroupViewModel(string name,string id, IEnumerable<T> items)
{
this.Id = id;
this.Name = name;
this.Items = items;
}
public IEnumerator<T> GetEnumerator()
{
return this.Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.Items.GetEnumerator();
}
}
然后我将列表分组如下:
var groupedList = from model in list1
group model by new { model.CompanyName,model.Id, model.Employees } into wordCollection
select new GroupViewModel<Employee>(wordCollection.Key.CompanyName, wordCollection.Key.Id, wordCollection.Key.Employees);