Group By either column using C# LINQ

女生的网名这么多〃 提交于 2020-01-03 17:52:27

问题


I have a set of Data with columns such as below

OffName,RO1,RO2,RO3

To explain further i use sample data as below:

OffName RO1    RO2   RO3 
A       John   Jack  Rob 
B       Earl   John  Carl 
C       Rob    Chris Kenny 
D       Rodney Carl  Jacob 

RO stands for Reporting Officer. Each Officer reports to upto 3 RO's.i need to make a report where i need to show a grouping by RO irrespective of the person is RO1 or RO2 or RO3 for the officer..John is RO1 for Officer A and RO2 for Officer B, so when grouped by RO under John i want both Officer A & B to be picked.Same for Carl is RO3 for Officer B and RO2 for Officer D so when grouped by Ro under Carl both Officer B & D to be picked..

So for the above data when grouped by RO's i want the result to be as

RO    OffName 
John     A 
         B 
Jack     A 
Rob      A 
         C 
Earl     B 
Carl     B 
         D 
Chris    C 
Kenny    C 
Rodney   D 
Jacob    D 

Any help would b great

Thanks.


回答1:


The easiest way is probably to "flatten" the problem and then do the group by:

    var query = officers.SelectMany(
        x => new[] {
            new { x.Name, RO = x.ReportingOfficer1 },
            new { x.Name, RO = x.ReportingOfficer2 },
            new { x.Name, RO = x.ReportingOfficer3 }
        }
    );
    var grouped = query.GroupBy(y => y.RO);
    foreach (var group in grouped) {
        foreach (var item in group) {
            Console.WriteLine(String.Format("{0}: {1}", item.RO, item.Name));
        }
    }

Here, I am assuming officers is a IEnumerable<Officer> where

class Officer {
    public string Name { get; set; }
    public string ReportingOfficer1 { get; set; }
    public string ReportingOfficer2 { get; set; }
    public string ReportingOfficer3 { get; set; }
}

With your sample data this is my output:

John: A
John: B
Jack: A
Rob: A
Rob: C
Earl: B
Carl: B
Carl: D
Chris: C
Kenny: C
Rodney: D
Jacob: D


来源:https://stackoverflow.com/questions/2153719/group-by-either-column-using-c-sharp-linq

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!