Learner
Learner

Reputation: 786

Add object and list of object inside another list c#

I am trying to add a list of List of Object and an object inside another list, for example;

public Class TeamRoles
{
    public Team Team{get;set;}
    public IEnumerable<Role> Roles{get;set;}
}

I am looping through another list of type TeamRoles and want to add each of that object after some modifications inside the List of TeamRoles, something like below;

public void SomeMethod()
{
    var teamsRoles = _client.GetAllTeamEmployeeRoles();
    var distinctTeams = teamsRoles.Select(x => x.Team).Distinct();
    var tRoles = new List<TeamRoles>();
    foreach (var team in distinctTeams)
    {
        var t = team;
        var roles = teamsRoles.Where(x => x.TeamId ==team.Id).Select(y => y.Role);
        tRoles.Add(new { t, roles}); //need this
    }
}

Please help me if you understand my question and ask for more info if you don't. Thanks in advance.

Upvotes: 1

Views: 2274

Answers (2)

ubi
ubi

Reputation: 4399

Not quite sure what your question is (is it that your program doesn't compile?)

You need to instantiate TeamRoles like

    foreach (var team in distinctTeams)
    {

        var t = team;
        var roles = teamsRoles.Where(x => x.TeamId ==team.Id).Select(y => y.Role);
        tRoles.Add(new TeamRoles { Team=t, Roles=roles }); //need this  <====
     }

Upvotes: 2

jtabuloc
jtabuloc

Reputation: 2535

You need to instantiate the TeamRoles and assign values to it, something like this:

var teamRoles = new TeamRoles
 {
   Roles = roles,
   Team = t
 };

tRoles.Add(teamRoles); //need this

Upvotes: 4

Related Questions