none
Lambda expression, Linq RRS feed

  • Question

  • Hi, I am having difficulties to understand the labda expression, I need to use LINQ join as a lambda expression.


    List<Contract> listContracts = contratoDAO.GetContracts();
    List<PriceContract> listPriceContract = blPriceContrato.GetPriceContractAll().ToList();


      public class Contract
        {       
            [DataMember]
            public Int32 IdContract { get; set; }     
            [DataMember]
            public PriceContract[] PriceContract { get; set; }
        }

    public class PriceContract
        {
            [DataMember]
            public int IdPriceContract { get; set; }      
            [DataMember]
            public int IdContract { get; set; }
    }


    I need to fill in for each contract your price list associated contract (Contract.PriceContract = List<PriceContract>) in a lambda expression

    I want the follow but using linq lambda expressions:

    var listaContratosLinq = from c in listaContratos select new Contrato { PrecioContrato = (from pc in listaPrecioContrato where pc.IdContrato == c.IdContrato select pc).ToArray(), IdContrato = c.IdContrato, Nombre = c.Nombre, FechaInicio = c.FechaInicio, FechaFin = c.FechaFin, ImporteMaximo = c.ImporteMaximo, AsignacionPresupuestaria = c.AsignacionPresupuestaria, CodigoContrato = c.CodigoContrato, Proveedor = c.Proveedor, ImporteTotalLecturas = c.ImporteTotalLecturas, ImporteTotalFacturas = c.ImporteTotalFacturas, };

    • Edited by ararb Monday, January 22, 2018 10:39 AM
    Monday, January 22, 2018 9:25 AM

All replies

  • https://paragy.wordpress.com/2010/11/18/sql-inner-join-with-linq-and-lambda-expression/

    You have the above example using lambda

    What I don't understand is why you simply didn't do the join in the DAL with the DAO and using the DTO pattern in shaping the DTO result brought back to the client  on the service-side -- not doing it on the client-side?

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    <copied>

    Flatten object graphs that contain nested objects, to make them more convenient for clients.

    <end>

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    An example of a DTO with a object graph of DTO(s) within the parent DTO.

    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    
    namespace Entities
    {
       [DataContract] 
        public class DTOStudent
        {
            
            private DTOResponse dtor = new DTOResponse();
    
            [DataMember]
            public Int32 StudentID { get; set; }
    
            [DataMember]
            public string LastName { get; set; }
    
            [DataMember]
            public string FirstName { get; set; }
    
            [DataMember]
            public DateTime? EnrollmentDate { get; set; }
    
            [DataMember]
            public virtual ICollection<DTOEnrollandCourse> EnrollsandCourses { get; set; }
    
            [DataMember]
            public DTOResponse DtoResponse
            {
                get { return dtor; }
                set { dtor = value; }
            } 
        }
    }
    
    ----------------------------------------------
    
    using System;
    using System.Runtime.Serialization;
    
    namespace Entities
    {
        public class DTOEnrollandCourse
        {
            [DataMember]
            public decimal? Grade { get; set; }
    
            [DataMember]
            public string Title { get; set; }
    
            [DataMember]
            public Int32? Credits { get; set; }
        }
    }
    
    -------------------------------------------------
    
    
    public class DAOStudent : IDAOStudent
        {
            public DTOStudent GetStudentById(Int32 id)
            {
                var dto = new DTOStudent();
                using (var context = new CUDataEntities())
                {
                    var student = (context.Students.Where(a => a.StudentID == id)).SingleOrDefault();
    
                    if (student != null)
                    {
                        dto.StudentID = student.StudentID;
                        dto.FirstName = student.FirstName;
                        dto.LastName = student.LastName;
                        dto.EnrollmentDate = student.EnrollmentDate;
    
                        var enrolllments =  new DAOEnrollment().GetEntrollmentsByStudentId(id).ToList();
                        var courses = new DAOCourse().GetCoursesByStudentCourseId(student.StudentID).ToList();
    
                        dto.EnrollsandCourses = (from a in enrolllments
                                      join b in courses on a.CourseID equals b.CourseID
                        select new  DTOEnrollandCourse()
                         { Title = b.Title, Credits = b.Credits, Grade = a.Grade }).ToList();
                    }
                }
    
                return dto;
            }

    Monday, January 22, 2018 10:21 AM
  • Hello arab,

    Try the below code, which use lambda expressions based on the above code. Because I don't know your class structure in details. I just define a simple class to replace it but the idea is the same.

        public class Contract
        {
            public Int32 IdContract { get; set; }
            public PriceContract[] PriceContract { get; set; }
        }
    
        public class PriceContract
        {
            public int IdPriceContract { get; set; }
            public int IdContract { get; set; }
        }
    
        public class Contrato
        {
            public PriceContract[] PrecioContrato { get; set; }
            public int IdContrato { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                List<Contract> listaContratos = new List<Contract> { new Contract { IdContract=1},new Contract { IdContract=2}};
                List<PriceContract> listaPrecioContrato = new List<PriceContract> { new PriceContract { IdContract = 2, IdPriceContract =  5}, new PriceContract { IdContract = 2, IdPriceContract = 6 }  };
    
                var listaContratosLinq = from c in listaContratos
                                         select new Contrato
                                         {
                                             PrecioContrato = (from pc in listaPrecioContrato where pc.IdContract == c.IdContract select pc).ToArray(),
                                             IdContrato = c.IdContract,                 
                                         };
                var listaContratosLambda = listaContratos.Select(x => new Contract {
                    PriceContract = listaPrecioContrato.Where(z => z.IdContract == x.IdContract).ToArray(),
                    IdContract = x.IdContract
                });
            }
        }

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, January 23, 2018 9:19 AM
    Moderator
  • Hello ararb,

    Is there any update or any other assistance I could provide? You could mark the helpful reply as answer if the issue has been solved. And if you have any concerns, please do not hesitate to let us know.

    Thanks a lot!

    Best regards,

    Neil Hu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, January 25, 2018 9:49 AM
    Moderator