Showing posts with label LINQ Tips and Tricks. Show all posts
Showing posts with label LINQ Tips and Tricks. Show all posts

Thursday, July 23, 2009

List to List conversion using LINQ




One of my requirment was to get the List object from a source and change it to another list with removing some of the properties. Here is how i have achived it

Project class
public class Project
{
public string ProjectCode { get; set; }
public string ProjectName { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string ManagerId { get; set; }
public string ClientId { get; set; }
}

Setting values to ProjectClass

List lstProject = new List
{ new Project { ProjectCode = "1" ,ProjectName ="CIS1", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG1" ,ClientId="CL1"},
new Project { ProjectCode = "2" ,ProjectName ="CIS2", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG2" ,ClientId="CL2"},
new Project { ProjectCode = "3" ,ProjectName ="CIS3", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG3" ,ClientId="CL3"},
new Project { ProjectCode = "4" ,ProjectName ="CIS4", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG4" ,ClientId="CL4"},
new Project { ProjectCode = "5" ,ProjectName ="CIS5", StartDate = "1/1/2000" ,EndDate = "2/2/2000" ,ManagerId ="MG5" ,ClientId="CL5"}
};

Converting the List to another List with some filters

List lstOutputProjects1 = (from projectlist in lstProject
select new Project
{
ProjectName = projectlist.ProjectName,
StartDate = projectlist.StartDate,
EndDate = projectlist.EndDate,
ManagerId = projectlist.ManagerId,
ClientId = projectlist.ClientId
}).ToList();

Hope this Helps :)