0

I have a result set which i get back from executing the stored procedure I am working with. Here is what the result set looks like for example:

 var staff = new Staff[]
        {
            new Staff{Code = 5, Name = "Sam", Team = "AB1"},
            new Staff{Code = 6, Name = "Dave", Team="RAB"},
            new Staff{Code = 6, Name = "Dave", Team="ABC"},
        };

A Staff member can operate in more than one team according to the data set i am dealing with.

What i want to do is group them in order to show the results like this:

Value  ChildValues
Dave   [RAB, ABC]
Sam    [AB1]

How can i achieve this? I have tried the following by duplicate the primary list but i know the below is incorrect:

 var query = staff.GroupJoin(staff, s => s.Code, 
            s => s.Code, (s, result) => new StaffResult(s.Name, result));

I appreciate the assistance regarding the above.

KI1
  • 907
  • 1
  • 13
  • 31

3 Answers3

1

You should use GroupBy method to achieve this.

var grouped = staff.GroupBy(x=>x.Name, x=>x.Team);

That statement groups you data by Name and each grouped will keep Teams.

You can find more info here https://msdn.microsoft.com/en-us/library/bb545971.aspx?f=255&MSPPError=-2147217396.

Hope it helps.

tym32167
  • 4,741
  • 2
  • 28
  • 32
1

Try following query:

var staff = new Staff[]
        {
            new Staff{Code = 5, Name = "Sam", Team = "AB1"},
            new Staff{Code = 6, Name = "Dave", Team="RAB"},
            new Staff{Code = 6, Name = "Dave", Team="ABC"},
        };

        var grouped = staff.GroupBy(m => m.Name)
            .Select(p => new { Value = p.Key, ChildVlues = p.Select(m => m.Team) })
            .ToList();

Here I grouped by Name. Than I created new anonymous type and added Key of group (represents Name) to Value. Also I added p.Select(m => m.Team) to ChildValues because you want collection of names.

kat1330
  • 5,134
  • 7
  • 38
  • 61
0

Check out the GroupBy statement in Linq:

https://msdn.microsoft.com/en-us/library/bb534304(v=vs.110).aspx

It would look like

var groupedStaff = staff.GroupBy(s=>s.Name, s=>S.Team);

This gets you a grouping that you can access through a foreach or another linq query if need be

Dudemanword
  • 710
  • 1
  • 6
  • 20