Setyo N
Setyo N

Reputation: 2103

How to obtain a list of elements contained in multiple list using LINQ?

Say I have codes:

  class Program
  {
    static void Main( string[] args )
    {
      Company companyA = new Company();
      Company companyB = new Company();
      companyA.Employees = new List<string> { "A1", "A2" };
      companyB.Employees = new List<string> { "B1", "B2" };

      List<Company> companyList = new List<Company> {companyA, companyB};
      List<string> allEmployees = new List<string>();
      foreach( Company company in companyList )
      {
        allEmployees.AddRange( company.Employees );
      }

      // ...
    }

    class Company
    {
      public List<string> Employees { get; set; }
    }
  }

I want to fill allEmployees with the employees from all companies in companyList.

Instead of using the above codes, is it possible to get the same result by using a single LINQ statement on companyList object? May be something like:

List<string> allEmployees  = companyList.Select( ...? )

Upvotes: 2

Views: 41

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You can use AddRange + SelectMany:

allEmployees.AddRange( companyList.SelectMany(c => c.Employees) );

If you don't want to add them to an already existing list but to create a new one:

List<string> allEmployees = companyList.SelectMany(c => c.Employees).ToList();

Upvotes: 2

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

Use SelectMany

List<string> allEmployees = companyList.SelectMany(x => x.Employees).ToList();

Upvotes: 4

Related Questions