STORM STORM - 3 months ago 16
C# Question

Joining to Lists via LINQ

I have two list of objects

Tasks

public string ProjectNumber { get; set; }
public string Name { get; set; }
public string ProjectManager { get; set; }
public string Customer { get; set; }


Projects

public string Number { get; set; }
public string Title { get; set; }
public string Manager { get; set; }
public string Customer { get; set; }


Example data

Tasks

Projectnumber | Name | ProjectManager | Customer
7780 | Buy container | NULL | NULL
7781 | Block budget | NULL | NULL


Projects

Nubmer | Title | Manager | Customer
7780 | Surface | Bill Gates | Microsoft
7781 | iWatch | Tim Cook | Apple


I want to get a
List<Task>
as result:

Projectnumber | Name | ProjectManager | Customer
7780 | Buy container | Bill Gates | Microsoft
7781 | Block budget | Tim Cook | Apple


What i tried so far:

List<Task> spTasks = SPRepo.GetAllTasksByResourceTeam();
List<Project> projects = PWARepo.GetAllProjects();

List<Task> joinedSPTasks = from a in spTasks
join b in projects on a.ProjectNumber equals b.Number
select new Task() {
a.Projectnumber = a.Projectnumber,
a.Name = a.Name,
a.ProjectManager = b.ProjectManager,
a.Customer = b.Manager
};


Why I can't assign values to properties? I get the following error in Visual Studio:

Error: Invalid anonymous type member decorator. Anonymous type members must be declared with a member assignment simple name or member access.


Note: These List of objects are coming from different sources. it is not possible to join them in the source system (for example a database via table joins)!

Answer

you are selecting the values in dynamic object. instead of using select new{, use select new Task{

        List<Task> joinedSPTasks = from a in spTasks
                join b in projects on a.ProjectNumber equals b.Number
                select new Task{
                    a.Projectnumber = a.Projectnumber,
                    a.Name = a.Name,
                    a.ProjectManager = b.ProjectManager,
                    a.Customer = b.Manager
                    };
Comments