Cameron Castillo
Cameron Castillo

Reputation: 2862

Linq: Count number of times a sub list appear in another list

I guess there must be an easy way, but not finding it. I would like to check whether a list of items, appear (completely or partially) in another list.

For example: Let's say I have people in a department as List 1. Then I have a list of sports with a list of participants in that sport.

Now I want to count, in how many sports does all the people of a department appear.

(I know some tables might not make sense when looking at it from a normalisation angle, but it is easier this way than to try and explain my real tables)

So I have something like this:

var peopleInDepartment = from d in Department_Members
                         group d by r.DepartmentID into g
                         select new
                         {
                            DepartmentID = g.Key,
                            TeamMembers = g.Select(r => d.PersonID).ToList()
              };

var peopleInTeam = from s in Sports
                   select new 
                   {
                      SportID = s.SportID,
                      PeopleInSport = s.Participants.Select(x => x.PersonID),
                      NoOfMatches = peopleInDepartment.Contains(s.Participants.Select(x => x.PersonID)).Count()
           };

The error here is that peopleInDepartment does not contain a definition for 'Contains'. Think I'm just in need of a new angle to look at this.

As the end result I would like print:

Department 1 : The Department participates in 3 sports

Department 2 : The Department participates in 0 sports

etc.

Upvotes: 1

Views: 78

Answers (1)

har07
har07

Reputation: 89325

Judging from the expected result, you should base the query on Department table like the first query. Maybe just include the sports count in the first query like so :

var peopleInDepartment = 
        from d in Department_Members
        group d by r.DepartmentID into g
        select new
        {
            DepartmentID = g.Key,
            TeamMembers = g.Select(r => d.PersonID).ToList(),
            NumberOfSports = Sports.Count(s => s.Participants
                                                .Any(p => g.Select(r => r.PersonID)
                                                           .Contains(p.PersonID)
                                                )
                                    )
        };

NumberOfSports should contains count of sports, where any of its participant is listed as member of current department (g.Select(r => r.PersonID).Contains(p.PersonID))).

Upvotes: 1

Related Questions