Wednesday, February 10, 2010

Build an Object from Other Object(s)

If there are no unknowns at design time, you can simply build a LINQ command that will accomplish this. In this example I have two classes – Person and FileFormat. I fill an IQueryable list of type Person and then use that list to populate an Generic list of type FileFormat. I then count the records that are copied to the new list.

LISTING 1.2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
 
namespace DynamicLINQ
{
    class Program
    {
        static void Main(string[] args)
        {
            IQueryable<Person> persons = new List<Person>{
                new Person{PersonID=1, CompanyID=1, FirstName="John", LastName="Smith"},
                new Person{PersonID=2, CompanyID=1, FirstName="Sam", LastName="Jones"},
                new Person{PersonID=3, CompanyID=1, FirstName="Jean", LastName="Smith"},
                new Person{PersonID=4, CompanyID=2, FirstName="Samantha", LastName="Maples"},
                new Person{PersonID=5, CompanyID=1, FirstName="Tom", LastName="Brown"}
            }.AsQueryable();
 
            List<FileFormat> fileFormat =
               (from p in persons
               where p.CompanyID == 1
select new FileFormat
              {
                    PersonID = p.PersonID,
                    CompanyID = p.CompanyID,
                    FirstName = p.FirstName,
                    LastName = p.LastName
              }).ToList();
 
            Console.WriteLine(fileFormat.Count.ToString());
            Console.ReadLine();
        }
    }
    public class Person
    {
        public int PersonID { get; set; }
        public int CompanyID { get; set; }
        public string FirstName { get;set; }
        public string LastName { get;set; }
    }
    public class FileFormat
    {
        public int PersonID { get; set; }
        public int CompanyID { get; set; }
        public string FirstName { get;set; }
        public string LastName { get;set; }
        public int CoverageID { get;set; }
        public int ProductID { get; set; }
        public double CoverageAmount { get;set; }
        public double CoverageCost { get;set; }
        public DateTime CoverageDate { get;set; }


The output from Listing 1.2 is 4 since PersonID 4 is eliminated by the LINQ query.

No comments:

Post a Comment