Josh
Josh

Reputation: 16567

Select parent and children when type is the same with linq

I have an object like this

public class Employee
{
    public int EmployeeId { get; set; }
    public string Name { get; set; }

    public IList<Employee> Employees{ get; set; }
}

What I would like to do is select all of the employees, plus the parent employee in a single collection. I want to have the parent as the first item in the collection for paging. Right now I am doing something like this

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);

Is there a better way to do this with a single linq statement?

Upvotes: 0

Views: 743

Answers (3)

Aliostad
Aliostad

Reputation: 81700

For a list of employees:

 employees.Concat(employees.SelectMany(x => x.Employees)).Skip(offset).Take(pageSize);

Example (outputs 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();
    }
}

Upvotes: 0

smartcaveman
smartcaveman

Reputation: 42276

Check out this question: How to use LINQ to select all descendants of a composite object .

Upvotes: 0

SLaks
SLaks

Reputation: 888213

Like this:

var pagedEmployees = new [] { emp }.Concat(allEmps).Skip(offset).Take(pageSize);

Upvotes: 3

Related Questions