jpavlov
jpavlov

Reputation: 2261

Returning Groupedby distinct linq values

I have a DataTable that looks like

Agency          | Contact         | Group
Agency1           person1           lunch runners
Agency1           person1           band
Agency1           person3           basketball
Agency2           person4           band

and I would like to group them by agency, and then by contact name. I have tried using linq 50 different ways but have hit a wall. Can someone shed a little light? thanks.

Upvotes: 0

Views: 60

Answers (3)

Moho
Moho

Reputation: 16498

var results = db.<EntityCollection>
    .ToLookup(a => a.Agency)
    .ToDictionary( lu => lu.Key, lu => lu.ToLookup( lui => lui.Contact ) );

Can then be accessed as follows:

results[<agencyName>][<contactName>]

Upvotes: 0

Eric Andres
Eric Andres

Reputation: 3417

collection.GroupBy(x => new { x.Agency, x.Contact }) should do it. This creates an anonymous object that is used for the key.

Note that you'll have to apply this general idea to the DataTable as @TimSchmelter does in his answer.

If you need a hierarchy of groups (i.e. the Agency1 group has a person1 group inside) you would do this:

collection.GroupBy(x => x.Agency).Select(x => x.GroupBy(y => y.Contact));

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460028

Use an anonymous type:

var groups = table.AsEnumerable()
    .GroupBy(r => new 
        { 
            Agency  = r.Field<string>("Agency"),
            Contact = r.Field<string>("Contact") 
        });

foreach (var agencyContactGroup in groups)
   Console.WriteLine("Agency: {0} Contact: {1} Groups: {2} Count: {3}"
       , agencyContactGroup.Key.Agency
       , agencyContactGroup.Key.Contact
       , string.Join(",", agencyContactGroup.Select(r => r.Field<string>("Group")))
       , agencyContactGroup.Count());

Output with your sample data:

Agency: Agency1 Contact: person1 Groups: lunch runners,band Count: 2
Agency: Agency1 Contact: person3 Groups: basketball         Count: 1
Agency: Agency2 Contact: person4 Groups: band               Count: 1

Upvotes: 2

Related Questions