简体   繁体   中英

How to GroupBy using LINQ query in C# when the key is to be the same type as your type T when grouping List<T>

I have a class as follows

class Employee
{
    string emp_id;
    string emp_name;
    string manager_id;
    bool isManager;
}

Data in my List is as follows

[1, Alex, 5, false]
[2, Charlie, 6, false]
[3, Aaron, 5, false]
[4, Brian, 6, false]
[5, Rock, "", true]
[6, William, "", true]

As you notice from above data the first 4 employees are not managers and hence have their manager_id populated but the last 2 are managers and hence do not have a manager_id. It can also be noticed by the bool values.

Now this should be grouped such that the employees under the common manager are grouped together and the key of that group should be their manager.

So based on the data it should group as follows (I am just typing names below for simplicity, in reality they all will be Employee Class Objects)

Group-1

Rock

  1. Alex
  2. Aaron

Group-2

William

  1. Charlie
  2. Brian

How do I achieve this in C# with LINQ?

var listOfCategories = new List<Employee>();
PopulateData(listOfCategories );
var listGroup = listOfCategories .GroupBy(x => x.manager_id);

But the key is now the Manager_id string. One way to get manager I can use Find and get the Employee object based on id.

I believe this can be achieved by LINQ.

I would be glad if someone can point me in the right direction. Thanks in Advance.

This is probably what you're looking for:

var listGroup = listOfCategories.GroupBy(x => listOfCategories.FirstOrDefault(y => y.emp_id == x.manager_id).emp_name);

Or if you want the keys to be full employee objects, you can remove .emp_name part from the lambda expression.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM