我有一个像这样的对象
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public IList<Employee> Employees{ get; set; }
}
我想要做的是在一个集合中选择所有员工以及父员工。我希望将父项作为分页集合中的第一项。现在我正在做这样的事情
Employee emp = getEmployeeFromService();
var allEmps = new List<Employee>();
allEmps.Add(emp);
allEmps.AddRange(emp.Employees);
var pagedEmployees= (from e in allEmps select e).Skip(offset).Take(pageSize);
使用单个linq语句有更好的方法吗?
答案 0 :(得分:3)
像这样:
var pagedEmployees = new [] { emp }.Concat(allEmps).Skip(offset).Take(pageSize);
答案 1 :(得分:0)
答案 2 :(得分:0)
获取员工名单:
employees.Concat(employees.SelectMany(x => x.Employees)).Skip(offset).Take(pageSize);
示例(输出7):
public class Employee
{
public Employee()
{
}
public Employee(int count)
{
Employees = new List<Employee>();
List<Employee> list = Employees as List<Employee>;
for (int i = 0; i < count; i++)
{
list.Add(new Employee());
}
}
public IEnumerable<Employee> Employees { get; set; }
}
class Program
{
static void Main(string[] args)
{
IEnumerable<Employee> employees = new Employee[]
{
new Employee(3),
new Employee(2)
};
IEnumerable<Employee> enumerable = employees.Concat(employees.SelectMany(x => x.Employees));
Console.WriteLine(enumerable.Count());
Console.Read();
}
}