Renjith
Renjith

Reputation: 682

How to group inner list data based on a key in outer list in c# linq

I have a class structure and data as follows:

   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"  } } }};

I want to group employeenames in Employee class based on outer company name in company class. How can i achieve this in linq.

Upvotes: 0

Views: 145

Answers (1)

Renjith
Renjith

Reputation: 682

I got it working, I have added a class that inherits 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();
    }
}

Then i have grouped the list as below:

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

Upvotes: 1

Related Questions