Output 2 fields from Linq Group By

I want to group by property WorkGroup.GroupId in class

public class Employee
{
  public int EmployeeID {get; set;}
  public Group WorkGroup {get; set;}
}

However, I need to derive a group name property (which may have duplicates, but will be identical between the same groupid)

Something like (this of course does not work):

var grps = from emp in Emps
          group emp by emp.WorkGroup.GroupID into g
          select new { GroupID = g.Key, Title = g.Key.WorkGroup.GroupTitle,  Employees = g };

I am looking for a conclusion that will allow me to draw:

foreach (var g in grps)
{
  Console.WriteLine(g.Title + "-" + g.GroupID);
  foreach (var e in g.Employees)
  {
     Console.WriteLine(e.EmployeeID);
  }
}
+3
source share
1 answer

Only group by identifier and tit:

var grps = 
    from emp in Emps
    group emp by new 
    { 
        GroupID = emp.WorkGroup.GroupID, 
        GroupTitle = emp.WorkGroup.GroupTitle 
    } into g
    select new 
    { 
        GroupID = g.Key.GroupID, 
        GroupTitle = g.Key.GroupTitle,  
        Employees = g
    };
+7
source

Source: https://habr.com/ru/post/1715390/


All Articles