Linq Left Join or similar - c#

I'm trying to fill my query with several table's info but I'm in trouble some fields are null or empty, so Im looking for a way to bring my info even if is null or empty or filled. Can you help me?? thanks!!
var generales = (from queja in db.RegistroQueja
join datosQueja in db.DatosQueja on queja.ID equals datosQueja.Id_Registro into g
from datosQueja in g.DefaultIfEmpty()
join estado in db.Estado on datosQueja.Estado equals estado.ID
join lugar in db.Lugar on datosQueja.Lugar equals lugar.ID
join genero in db.Genero on datosQueja.Genero equals genero.ID
join tipoUser in db.Clasificacion on datosQueja.Clasificacion equals tipoUser.ID
join calDetalle in db.CalificacionDetalle on queja.ID equals calDetalle.Id_Registro into f
from calDetalle in f.DefaultIfEmpty()
join medioC in db.Medio_Captacion on calDetalle.Medio_Captacion equals medioC.ID
join temaCorp in db.Dimension on calDetalle.Dimension equals temaCorp.ID
join tipoInc in db.Tipo_Incidencia on calDetalle.Tipo_Incidencia equals tipoInc.ID
join dataIncidencia in db.RegistroIncidencia on calDetalle.Incidencia equals dataIncidencia.Id
join incidencia in db.TemaIncidencia on dataIncidencia.TemaIncidencia equals incidencia.IDTemaIncidencia
join estatus in db.Estatus_SAC on queja.Estatus equals estatus.Id
join contexto in db.Contextualizacion on queja.ID equals contexto.Id_Registro into e
from contexto in e.DefaultIfEmpty()
join procInt0 in db.ProcesoInterno on queja.ID equals procInt0.Id_Registro into d
from procInt0 in d.DefaultIfEmpty()
join cierre in db.Cierre_Seguimiento on queja.ID equals cierre.Id_Registro into c
from cierre in c.DefaultIfEmpty()
join tipoCierre in db.Tipo_Cierre on cierre.Tipo_Cierre equals tipoCierre.Id
join paises in db.Pais on datosQueja.Pais equals paises.Id
//join regiones in db.Region on datosQueja.Estado equals regiones.Id
join sitios in db.Sitio on datosQueja.Unidad equals sitios.Id
where queja.Fecha_creacion >= fechaI && queja.Fecha_modificacion <= fechaC
select new
{
//Campos informacion de contacto
Folio = queja.Folio,
CasoAnonimo = queja.Queja_Anonima,
NombreContacto = String.IsNullOrEmpty(g.Nombre) ? "" : datosQueja.Nombre,
TelefonoContacto = String.IsNullOrEmpty(datosQueja.Telefono) ? "" : datosQueja.Telefono,
Telefono2 = datosQueja.Extencion,
GeneroInt = datosQueja.Genero,
Genero = String.IsNullOrEmpty(genero.Genero1) ? "" : genero.Genero1,
EdadContacto = datosQueja.Edad,
Tipo = String.IsNullOrEmpty(datosQueja.Tipo) ? "" : datosQueja.Tipo,
CorreoContacto = String.IsNullOrEmpty(datosQueja.Correo) ? "" : datosQueja.Correo,
TipoUsuario = datosQueja.Clasificacion,
TipoUsuarioNombre = String.IsNullOrEmpty(tipoUser.Nombre) ? "" : tipoUser.Nombre,
EspecificarContacto = String.IsNullOrEmpty(datosQueja.Especificar) ? "" : datosQueja.Especificar,
// Campos ubicacion
Pais = datosQueja.Pais,
PaisNombre = paises.Nombre,
Estados = datosQueja.Estado,
EstadosNombre = estado.Nombre,
OtroEstado = datosQueja.Estado_Otro,
Lugar = datosQueja.Lugar,
LugarNombre = lugar.Nombre,
CodigoP = datosQueja.CP,
Colonia = datosQueja.Colonia,
Unidad = datosQueja.Unidad,
UnidadNombre = sitios.Nombre,
Direccion = datosQueja.Direccion,
Especifiaciones = datosQueja.Especificaciones,
FechaEvento = datosQueja.Fecha_Evento,
DescripcionCaso = datosQueja.Descripcion,
Estatus = queja.Estatus,
EstatusNombre = estatus.Nombre,
MedioCapacitacion = calDetalle.Medio_Captacion,
MedioCaptacionNombre = medioC.Nombre,
Dimension = calDetalle.Dimension,
TemaCorporativoNombre = temaCorp.Nombre,
TipoIncidencia = calDetalle.Tipo_Incidencia,
TipoIncidenciaNombre = tipoInc.Nombre,
Incidencia = calDetalle.Incidencia,
IncidenciaNombre = incidencia.Nombre,
FechaInicio = queja.Fecha_creacion,
FechaFin = queja.Fecha_modificacion,
//Contextualizacion
WhatsApp = contexto.WhatsApp,
Correo = contexto.Correo,
Llamada = contexto.Llamada,
ObservacionesContext = contexto.Observaciones,
Confirmacion_Recibido = contexto.Confirmacion_Recibido,
//Proceso Interno
ValidacionExterna = procInt0.Validacion_Externa,
JustificacionValidacion = String.IsNullOrEmpty(procInt0.Justificacion_Validacion) ? "" : procInt0.Justificacion_Validacion,
RespaldoJuridico = procInt0.Respaldo_Juridico,
JustificacionRespaldo = String.IsNullOrEmpty(procInt0.Justificacion_Respaldo) ? "" : procInt0.Justificacion_Respaldo,
CierreProceso = procInt0.Cierre_Proceso,
// Cierre
Tipo_Cierre = cierre.Tipo_Cierre,
Tipo_Cierre_Nombre = tipoCierre.Nombre,
Observaciones = cierre.Observaciones,
Testimonio = cierre.Testimonio,
Expediente_Respaldo = cierre.Expediente_Respaldo,
Oficio_Tercero = cierre.Oficio_Tercero,
Bitacoras_Comunitarias = cierre.Bitacoras_Comunitarias,
Memoria_Inicial = cierre.Memoria_Inicial,
Memoria_Final = cierre.Memoria_Final,
Recibo_Deducible = cierre.Recibo_Deducible,
Oficio_Agradecimiento = cierre.Oficio_Agradecimiento,
Resultados_Estudios = cierre.Resultados_Estudios,
Correo_Seguimiento = cierre.Correo_Seguimiento,
Comunicados_Oficiales = cierre.Comunicados_Oficiales,
Notas_Periodisticas = cierre.Notas_Periodisticas,
Respaldo_Redes = cierre.Respaldo_Redes,
Otros = cierre.Otros,
Comunicacion = cierre.Comunicacion,
Dialogo_Directo = cierre.Dialogo_Directo,
Comunicacion_Clave = cierre.Comunicacion_Clave,
Difusion_Redes = cierre.Difusion_Redes,
Cierre_Desarrollo = cierre.Cierre_Desarrollo,
Cierre_SAC = cierre.Cierre_SAC,
}).Distinct().ToList().Select(p => new DataGeneral
{
Folio = p.Folio,
CasoAnonimo = p.CasoAnonimo,
NombreContacto = p.NombreContacto,
TelefonoContacto = p.TelefonoContacto,
Telefono2 = p.Telefono2,
GeneroInt = p.GeneroInt,
Genero = p.Genero,
EdadContacto = p.EdadContacto,
Tipo = p.Tipo,
CorreoContacto = p.CorreoContacto,
TipoUsuario = p.TipoUsuario,
TipoUsuarioNombre = p.TipoUsuarioNombre,
EspecificarContacto = p.EspecificarContacto,
//Campos ubicacion
Pais = p.Pais,
PaisNombre = p.PaisNombre,
Estado = p.Estados,
EstadosNombre = p.EstadosNombre,
OtroEstado = p.OtroEstado,
Lugar = p.Lugar,
LugarNombre = p.LugarNombre,
CodigoP = p.CodigoP,
Colonia = p.Colonia,
Unidad = p.Unidad,
UnidadNombre = p.UnidadNombre,
Direccion = p.Direccion,
Especifiaciones = p.Especifiaciones,
FechaEvento = p.FechaEvento,
DescripcionCaso = p.DescripcionCaso,
MedioCapacitacion = p.MedioCapacitacion,
MedioCaptacionNombre = p.MedioCaptacionNombre,
TemaCorporativo = p.Dimension,
TemaCorporativoNombre = p.TemaCorporativoNombre,
TipoIncidencia = p.TipoIncidencia,
TipoIncidenciaNombre = p.TipoIncidenciaNombre,
Incidencia = p.Incidencia,
IncidenciaNombre = p.IncidenciaNombre,
Estatus = p.Estatus,
EstatusNombre = p.EstatusNombre,
FechaInicio = p.FechaInicio,
FechaFin = p.FechaFin,
//Context
WhatsApp = p.WhatsApp,
Correo = p.Correo,
Llamada = p.Llamada,
ObservacionesContext = p.ObservacionesContext,
Confirmacion_Recibido = p.Confirmacion_Recibido,
//proceso Intern
ValidacionExterna = p.ValidacionExterna,
JustificacionValidacion = p.JustificacionValidacion,
JustificacionRespaldo = p.JustificacionRespaldo,
RespaldoJuridico = p.RespaldoJuridico,
CierreProceso = p.CierreProceso,
//// cierre
Tipo_Cierre = p.Tipo_Cierre,
Tipo_CierreNombre = p.Tipo_Cierre_Nombre,
Observaciones = p.Observaciones,
Testimonio = p.Testimonio,
Expediente_Respaldo = p.Expediente_Respaldo,
Oficio_Tercero = p.Oficio_Tercero,
Bitacoras_Comunitarias = p.Bitacoras_Comunitarias,
Memoria_Inicial = p.Memoria_Inicial,
Memoria_Final = p.Memoria_Final,
Recibo_Deducible = p.Recibo_Deducible,
Oficio_Agradecimiento = p.Oficio_Agradecimiento,
Resultados_Estudios = p.Resultados_Estudios,
Correo_Seguimiento = p.Correo_Seguimiento,
Comunicados_Oficiales = p.Comunicados_Oficiales,
Notas_Periodisticas = p.Notas_Periodisticas,
Respaldo_Redes = p.Respaldo_Redes,
Otros = p.Otros,
Comunicacion = p.Comunicacion,
Dialogo_Directo = p.Dialogo_Directo,
Comunicacion_Clave = p.Comunicacion_Clave,
Difusion_Redes = p.Difusion_Redes,
Cierre_Desarrollo = p.Cierre_Desarrollo,
Cierre_SAC = p.Cierre_SAC,
}).DefaultIfEmpty();

I m using this code in my projects
public IQueryable<AgcTaskType> GetByAgcOfficerId(Guid id)
{
return from entity in GetQueryable()
join companyX in _context.Companies on entity.CompanyId equals companyX.Id into companyJoin
from company in companyJoin.DefaultIfEmpty()
join cwrX in _context.CompanyWorkingRegions.GetByAgcOfficer(id) on company.Id equals cwrX.CompanyId into cwrJoin
from cwr in cwrJoin.DefaultIfEmpty()
where !entity.CompanyId.HasValue || (entity.CompanyId.HasValue && cwr != null)
select entity;
}
In this example, this part of code
join companyX in _context.Companies on entity.CompanyId equals companyX.Id into companyJoin
from company in companyJoin.DefaultIfEmpty()
is should work for you.
You already use it in your code, just check your algorithm.

Related

Return two lists to view

I'm trying to return two lists to my view, these lists help me fill some webgrid, I searched the web and I can not find a solution, I'm new to this
My Controller
public ActionResult Index()
{
List<WebGrid> list = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Cat_Proyecto
join b in dc.Cat_Pais on a.Id_Pais equals b.ID
join c in dc.Cat_estado on a.Id_Estado equals c.Id
select new WebGrid
{
ID = a.ID,
ID_kEY = a.ID_kEY,
Cliente = a.Cliente,
Tipo_servicio = a.Tipo_servicio,
Descripcion = a.Descripcion,
Contratista = a.Contratista,
INCA_PM = a.INCA_PM,
Importe_INCA = a.Importe_INCA,
Importe_Cliente = a.Importe_Cliente,
calle = a.calle,
colonia = a.colonia,
Estado = c.Estado,
Pais = b.Pais
});
list = v.ToList();
}
List<WebGrid> list_Usuario = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Usuarios
select new WebGrid
{
Usuario = a.Usuario,
nombres = a.Nombres,
apellidos = a.Apellido_Paterno,
empresa = a.Area_Empresa,
estatus_Usuario = a.Estatus,
alcance = a.Id_Alcance
});
list_Usuario = v.ToList();
}
return View("../Admin/Administrador", list, list_Usuario);
}
in the return View tried to return to the view and my two lists to fill two web grid, only that I get an error, but I want to know how together these two lists so I can fill my grid
As both the list are of same type i.e List<WebGrid>
you can use AddRange and concat both the list and pass to view
public ActionResult Index()
{
List<WebGrid> list = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Cat_Proyecto
join b in dc.Cat_Pais on a.Id_Pais equals b.ID
join c in dc.Cat_estado on a.Id_Estado equals c.Id
select new WebGrid
{
ID = a.ID,
ID_kEY = a.ID_kEY,
Cliente = a.Cliente,
Tipo_servicio = a.Tipo_servicio,
Descripcion = a.Descripcion,
Contratista = a.Contratista,
INCA_PM = a.INCA_PM,
Importe_INCA = a.Importe_INCA,
Importe_Cliente = a.Importe_Cliente,
calle = a.calle,
colonia = a.colonia,
Estado = c.Estado,
Pais = b.Pais
});
list = v.ToList();
}
List<WebGrid> list_Usuario = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Usuarios
select new WebGrid
{
Usuario = a.Usuario,
nombres = a.Nombres,
apellidos = a.Apellido_Paterno,
empresa = a.Area_Empresa,
estatus_Usuario = a.Estatus,
alcance = a.Id_Alcance
});
list_Usuario = v.ToList();
}
list.AddRange(list_Usuario);
return View("../Admin/Administrador", list);
}
or else you can create a class and use it
public class WebGridModel
{
public List<WebGrid> List1{get;set;}
public List<WebGrid> List2{get;set;}
}
and use it like this
public ActionResult Index()
{
List<WebGrid> list = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Cat_Proyecto
join b in dc.Cat_Pais on a.Id_Pais equals b.ID
join c in dc.Cat_estado on a.Id_Estado equals c.Id
select new WebGrid
{
ID = a.ID,
ID_kEY = a.ID_kEY,
Cliente = a.Cliente,
Tipo_servicio = a.Tipo_servicio,
Descripcion = a.Descripcion,
Contratista = a.Contratista,
INCA_PM = a.INCA_PM,
Importe_INCA = a.Importe_INCA,
Importe_Cliente = a.Importe_Cliente,
calle = a.calle,
colonia = a.colonia,
Estado = c.Estado,
Pais = b.Pais
});
list = v.ToList();
}
List<WebGrid> list_Usuario = new List<WebGrid>();
using (Web_INCAEntities dc = new Web_INCAEntities())
{
var v = (from a in dc.Usuarios
select new WebGrid
{
Usuario = a.Usuario,
nombres = a.Nombres,
apellidos = a.Apellido_Paterno,
empresa = a.Area_Empresa,
estatus_Usuario = a.Estatus,
alcance = a.Id_Alcance
});
list_Usuario = v.ToList();
}
var returnObj = new WebGridModel
{
List1= list;
List2=list_Usuario ;
}
return View("../Admin/Administrador", returnObj );
}

linq many to many query inside select

Here is my attempt to make a many to many linq request, but it doesn't work as expected. CVVM class has a property ICollection<FormationVM> Formations
var cv = (
from c in context.CVs
where c.Id == id
select new CVVM
{
Id = id,
Formations =
from f in context.Formations
from c2 in context.CVs
where c2.Id == id
select new FormationVM
{
Id = form.Id,
DateDebut = form.DateDebut,
DateFin = form.DateFin,
Ecole = form.Ecole,
Description = form.Description,
Diplome = form.Diplome
}
}).FirstOrDefault();
Why does Model.Formations.Count() return 3 instead of 2 in my View please ?
Ok i found the solution. This code works :
using (Context context = new Context())
{
var cv =
(
from c in context.CVs
where c.Id == id && c.PersonneId == userId
select new CVVM
{
Titre = c.Titre,
MontrerPhoto = c.MontrerPhoto,
Layout = c.Layout,
Id = id,
FormAction = "EditionTraitement",
FormTitre = "Edition de ce CV",
Formations = from form in c.Formations
where c.Id == id && c.PersonneId == userId
select new FormationVM
{
Id = form.Id,
DateDebut = form.DateDebut,
DateFin = form.DateFin,
Ecole = form.Ecole,
Description = form.Description,
Diplome = form.Diplome
}
}).FirstOrDefault();
}

C# LINQ Query Resulting in DB2 Error The data types of the result-expressions of a CASE expression or DECODE function are not compatible

I have a query, it needs to select from a DB2 DB but the records need to be grouped by one column (PeopleID) so that the Applications can be put into a list for returning the required Data Object. Whilst I can see multiple areas that create CASE statements, I do not see any returning different values.
I have gone through the resulting query that is sent to DB2, it generates the same error but I cannot find anything obvious in that either. I would post the resulting query here but it goes over the character limit.
I have been combing this code and the resulting DB2 query for the last two days and cannot find the source of the data-type mismatch.
In the joins I do have to cast some Non-Nullable values to Nullable, I cannot see any reason that would create conflict.
Error
SQL Error [42804]: The data types of the result-expressions of a CASE expression or DECODE function are not compatible.. SQLCODE=-581, SQLSTATE=42804, DRIVER=4.21.29
The data types of the result-expressions of a CASE expression or DECODE function are not compatible.. SQLCODE=-581, SQLSTATE=42804, DRIVER=4.21.29
An error occurred during implicit system action type "2". Information returned for the error includes SQLCODE "-581", SQLSTATE "42804" and message tokens "42804".. SQLCODE=-727, SQLSTATE=56098, DRIVER=4.21.29
C# LINQ Query
IEnumerable<PersonRegistrationInformation> results = (from data in (from participant_app in DBContext.PARTICIPANT_APPLICATION
join people_vendor in DBContext.PEOPLE_VENDORS on participant_app.PEOPLE_ID equals people_vendor.PEOPLE_VENDORS_ID into tmppeople_vendor
from people_vendor in tmppeople_vendor.DefaultIfEmpty()
join reg_member_supp_app in DBContext.REG_MEMBER_SUPP_APP
on new { REG_MEMBER_SUPP_APP_ID = (participant_app.REG_MEMBER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_member_supp_app.REG_MEMBER_SUPP_APP_ID, reg_member_supp_app.ELIG_DECISION_ICD } into tmpreg_member
from reg_member_supp_app in tmpreg_member.DefaultIfEmpty()
join reg_trainer_supp_app in DBContext.REG_TRAINER_SUPP_APP
on new { REG_TRAINER_SUPP_APP_ID = (participant_app.REG_TRAINER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_trainer_supp_app.REG_TRAINER_SUPP_APP_ID, reg_trainer_supp_app.ELIG_DECISION_ICD } into tmpreg_trainer
from reg_trainer_supp_app in tmpreg_trainer.DefaultIfEmpty()
where reg_member_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
&& reg_trainer_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
select new PersonRegistrationInformationTableInformation()
{
PeopleID = !string.IsNullOrEmpty(participant_app.PEOPLE_ID) ? participant_app.PEOPLE_ID.ToUpper().Trim() : null,
FirstName = !string.IsNullOrEmpty(people_vendor.FIRST_NAME) ? people_vendor.FIRST_NAME.Trim() : null,
LastName = !string.IsNullOrEmpty(people_vendor.LAST_NAME) ? people_vendor.LAST_NAME.Trim() : null,
RegistryMemberSupplementApplication = reg_member_supp_app,
RegistryTrainerSupplementApplication = reg_trainer_supp_app,
})
group data by data.PeopleID into grp_data
select new PersonRegistrationInformation()
{
PeopleID = grp_data.Key,
FirstName = grp_data.FirstOrDefault().FirstName,
LastName = grp_data.FirstOrDefault().LastName,
RegistryMemberApplications = grp_data.Select(data => new RegistryMemberSupplementApplication()
{
RegistryMemberSupplementApplicationID = data.RegistryMemberSupplementApplication.REG_MEMBER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryMemberSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryMemberSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryMemberSupplementApplication.APPLICANT_SIGNED_DATE,
ParentSignedDate = data.RegistryMemberSupplementApplication.PARENT_SIGNED_DATE,
BasicTranscriptReviewICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_REVIEW_ICD,
BasicTranscriptStatusICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_STATUS_ICD,
TranscriptsReadyDate = data.RegistryMemberSupplementApplication.TRANSCRIPTS_READY_DATE,
SubmitPreviousTrainingICD = data.RegistryMemberSupplementApplication.SUBMIT_PREV_TRAIN_ICD,
HowLearnICD = data.RegistryMemberSupplementApplication.HOW_LEARN_ICD,
IsRenewal = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RENEWAL_FG) ? (bool?)data.RegistryMemberSupplementApplication.RENEWAL_FG.ToUpper().Trim().Equals("Y") : null,
IsReconsideration = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RECONSIDERATION_FG) ? (bool?)data.RegistryMemberSupplementApplication.RECONSIDERATION_FG.ToUpper().Trim().Equals("Y") : null,
ReleaseOfInformationICD = data.RegistryMemberSupplementApplication.RELEASE_INFO_ICD,
PersonJobID = data.RegistryMemberSupplementApplication.PERSON_JOB_ID,
EligibilityDecisionICD = data.RegistryMemberSupplementApplication.ELIG_DECISION_ICD,
EligibilityDenialReasonICD = data.RegistryMemberSupplementApplication.ELIG_DENIAL_REASON_ICD,
EligibilityDecisionDate = data.RegistryMemberSupplementApplication.ELIG_DECISION_DATE,
CurrentEligibilityDate = data.RegistryMemberSupplementApplication.CURR_ELIG_DATE,
RenewEligibilityDate = data.RegistryMemberSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryMemberSupplementApplication.RENEW_NOTICE_DATE,
ParticipantApplicationID = data.RegistryMemberSupplementApplication.PARTICIPANT_APPLICATION_ID,
PendingType = data.RegistryMemberSupplementApplication.PENDING_TYPE,
ReferringProgram = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.REFERRING_PROGRAM) ? data.RegistryMemberSupplementApplication.REFERRING_PROGRAM.Trim() : null,
BTRCompletedDate = data.RegistryMemberSupplementApplication.BTR_COMPLETED_DATE,
CreateDate = data.RegistryMemberSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.CREATE_USER) ? data.RegistryMemberSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryMemberSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.UPDATE_USER) ? data.RegistryMemberSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryMemberSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
}),
RegistryTrainerApplications = grp_data.Select(data=> new RegistryTrainerSupplementApplication()
{
RegistryTrainerSupplementApplicationID = data.RegistryTrainerSupplementApplication.REG_TRAINER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryTrainerSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryTrainerSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryTrainerSupplementApplication.APPLICANT_SIGNED_DATE,
ReleaseOfInformationICD = data.RegistryTrainerSupplementApplication.RELEASE_INFO_ICD,
EligibilityDecisionICD = data.RegistryTrainerSupplementApplication.ELIG_DECISION_ICD,
EligibilityDecisionDate = data.RegistryTrainerSupplementApplication.ELIG_DECISION_DATE,
EligibilityDenialReasonICD = data.RegistryTrainerSupplementApplication.ELIG_DENIAL_REASON_ICD,
RenewEligibilityDate = data.RegistryTrainerSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryTrainerSupplementApplication.RENEW_NOTICE_DATE,
TrainerID = data.RegistryTrainerSupplementApplication.TRAINER_ID,
PendingType = data.RegistryTrainerSupplementApplication.PENDING_TYPE,
CurrentEligibilityDate = data.RegistryTrainerSupplementApplication.CURR_ELIG_DATE,
CreateDate = data.RegistryTrainerSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.CREATE_USER) ? data.RegistryTrainerSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryTrainerSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.UPDATE_USER) ? data.RegistryTrainerSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryTrainerSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
})
}).AsEnumerable();
I seperated out the two linq queries and it appears to work just fine...
IEnumerable<PersonRegistrationInformationTableInformation> results = (from data in (from participant_app in DBContext.PARTICIPANT_APPLICATION
join people_vendor in DBContext.PEOPLE_VENDORS on participant_app.PEOPLE_ID equals people_vendor.PEOPLE_VENDORS_ID into tmppeople_vendor
from people_vendor in tmppeople_vendor.DefaultIfEmpty()
join reg_member_supp_app in DBContext.REG_MEMBER_SUPP_APP
on new { REG_MEMBER_SUPP_APP_ID = (participant_app.REG_MEMBER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_member_supp_app.REG_MEMBER_SUPP_APP_ID, reg_member_supp_app.ELIG_DECISION_ICD } into tmpreg_member
from reg_member_supp_app in tmpreg_member.DefaultIfEmpty()
join reg_trainer_supp_app in DBContext.REG_TRAINER_SUPP_APP
on new { REG_TRAINER_SUPP_APP_ID = (participant_app.REG_TRAINER_SUPP_APP_ID ?? -1), ELIG_DECISION_ICD = (int?)10591 }
equals new { reg_trainer_supp_app.REG_TRAINER_SUPP_APP_ID, reg_trainer_supp_app.ELIG_DECISION_ICD } into tmpreg_trainer
from reg_trainer_supp_app in tmpreg_trainer.DefaultIfEmpty()
where reg_member_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
&& reg_trainer_supp_app.RENEW_ELIG_DATE >= DateTime.Today.Date
select new PersonRegistrationInformationTableInformation()
{
PeopleID = !string.IsNullOrEmpty(participant_app.PEOPLE_ID) ? participant_app.PEOPLE_ID.ToUpper().Trim() : null,
FirstName = !string.IsNullOrEmpty(people_vendor.FIRST_NAME) ? people_vendor.FIRST_NAME.Trim() : null,
LastName = !string.IsNullOrEmpty(people_vendor.LAST_NAME) ? people_vendor.LAST_NAME.Trim() : null,
RegistryMemberSupplementApplication = reg_member_supp_app,
RegistryTrainerSupplementApplication = reg_trainer_supp_app,
})
IEnumerable<PersonRegistrationInformation> tableinfo = from data in results
group data by data.PeopleID into grp_data
select new PersonRegistrationInformation()
{
PeopleID = grp_data.Key,
FirstName = grp_data.FirstOrDefault().FirstName,
LastName = grp_data.FirstOrDefault().LastName,
RegistryMemberApplications = grp_data.Select(data => new RegistryMemberSupplementApplication()
{
RegistryMemberSupplementApplicationID = data.RegistryMemberSupplementApplication.REG_MEMBER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryMemberSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryMemberSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryMemberSupplementApplication.APPLICANT_SIGNED_DATE,
ParentSignedDate = data.RegistryMemberSupplementApplication.PARENT_SIGNED_DATE,
BasicTranscriptReviewICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_REVIEW_ICD,
BasicTranscriptStatusICD = data.RegistryMemberSupplementApplication.BASIC_TRANSCRIPT_STATUS_ICD,
TranscriptsReadyDate = data.RegistryMemberSupplementApplication.TRANSCRIPTS_READY_DATE,
SubmitPreviousTrainingICD = data.RegistryMemberSupplementApplication.SUBMIT_PREV_TRAIN_ICD,
HowLearnICD = data.RegistryMemberSupplementApplication.HOW_LEARN_ICD,
IsRenewal = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RENEWAL_FG) ? (bool?)data.RegistryMemberSupplementApplication.RENEWAL_FG.ToUpper().Trim().Equals("Y") : null,
IsReconsideration = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.RECONSIDERATION_FG) ? (bool?)data.RegistryMemberSupplementApplication.RECONSIDERATION_FG.ToUpper().Trim().Equals("Y") : null,
ReleaseOfInformationICD = data.RegistryMemberSupplementApplication.RELEASE_INFO_ICD,
PersonJobID = data.RegistryMemberSupplementApplication.PERSON_JOB_ID,
EligibilityDecisionICD = data.RegistryMemberSupplementApplication.ELIG_DECISION_ICD,
EligibilityDenialReasonICD = data.RegistryMemberSupplementApplication.ELIG_DENIAL_REASON_ICD,
EligibilityDecisionDate = data.RegistryMemberSupplementApplication.ELIG_DECISION_DATE,
CurrentEligibilityDate = data.RegistryMemberSupplementApplication.CURR_ELIG_DATE,
RenewEligibilityDate = data.RegistryMemberSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryMemberSupplementApplication.RENEW_NOTICE_DATE,
ParticipantApplicationID = data.RegistryMemberSupplementApplication.PARTICIPANT_APPLICATION_ID,
PendingType = data.RegistryMemberSupplementApplication.PENDING_TYPE,
ReferringProgram = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.REFERRING_PROGRAM) ? data.RegistryMemberSupplementApplication.REFERRING_PROGRAM.Trim() : null,
BTRCompletedDate = data.RegistryMemberSupplementApplication.BTR_COMPLETED_DATE,
CreateDate = data.RegistryMemberSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.CREATE_USER) ? data.RegistryMemberSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryMemberSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryMemberSupplementApplication.UPDATE_USER) ? data.RegistryMemberSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryMemberSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
}),
RegistryTrainerApplications = grp_data.Select(data=> new RegistryTrainerSupplementApplication()
{
RegistryTrainerSupplementApplicationID = data.RegistryTrainerSupplementApplication.REG_TRAINER_SUPP_APP_ID,
ApplicationTypeICD = data.RegistryTrainerSupplementApplication.APPL_TYPE_ICD,
ReceiptDate = data.RegistryTrainerSupplementApplication.RECEIPT_DATE,
ApplicantSignedDate = data.RegistryTrainerSupplementApplication.APPLICANT_SIGNED_DATE,
ReleaseOfInformationICD = data.RegistryTrainerSupplementApplication.RELEASE_INFO_ICD,
EligibilityDecisionICD = data.RegistryTrainerSupplementApplication.ELIG_DECISION_ICD,
EligibilityDecisionDate = data.RegistryTrainerSupplementApplication.ELIG_DECISION_DATE,
EligibilityDenialReasonICD = data.RegistryTrainerSupplementApplication.ELIG_DENIAL_REASON_ICD,
RenewEligibilityDate = data.RegistryTrainerSupplementApplication.RENEW_ELIG_DATE,
RenewNoticeDate = data.RegistryTrainerSupplementApplication.RENEW_NOTICE_DATE,
TrainerID = data.RegistryTrainerSupplementApplication.TRAINER_ID,
PendingType = data.RegistryTrainerSupplementApplication.PENDING_TYPE,
CurrentEligibilityDate = data.RegistryTrainerSupplementApplication.CURR_ELIG_DATE,
CreateDate = data.RegistryTrainerSupplementApplication.CREATE_DATE,
CreateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.CREATE_USER) ? data.RegistryTrainerSupplementApplication.CREATE_USER.Trim() : null,
UpdateDate = data.RegistryTrainerSupplementApplication.UPDATE_DATE,
UpdateUser = !string.IsNullOrEmpty(data.RegistryTrainerSupplementApplication.UPDATE_USER) ? data.RegistryTrainerSupplementApplication.UPDATE_USER.Trim() : null,
IsDeleted = data.RegistryTrainerSupplementApplication.DELETED_IND.ToUpper().Trim().Equals("Y"),
})
});

c# Sort Combined List by Ascending

I combined 2 lists in 1 list with some columns and I'd like to order it by Ascending. The column that I want to order is HODD.
I tried to read the others answers about this problem, but I don't know how I can apply them to my code.
This is my code:
var data1 = File.ReadAllLines("read" + campionatoselezTxt.Text + "stats.txt").ToList();
var data2 = File.ReadAllLines("read" + campionatoselezTxt.Text + "bex.txt").ToList();
var dataList1 = new List<Data1>();
foreach (var data in data1)
{
var columns = data.Split(';');
dataList1.Add(new Data1
{
Campionato = columns[0],
Data = columns[1],
Home = columns[2],
Away = columns[3],
HSFT = int.Parse(columns[4]),
ASFT = int.Parse(columns[5]),
HSHT = int.Parse(columns[6]),
ASHT = int.Parse(columns[7]),
HSSH = int.Parse(columns[8]),
ASSH = int.Parse(columns[9])
//other int properties
});
}
var dataList2 = new List<Data2>();
foreach (var data in data2)
{
var columns = data.Split(';');
dataList2.Add(new Data2
{
Home = columns[0],
Away = columns[1],
HODD = columns[4],
XODD = columns[5],
AODD = columns[6],
});
}
var combinedDataList = from d1 in dataList1
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in dataList2 on new { d1.Home, d1.Away } equals new { d2.Home, d2.Away }
select new CombinedData
{
Campionato = d1.Campionato,
Data = d1.Data,
Home = d2.Home,
Away = d2.Away,
HSFT = d1.HSFT,
ASFT = d1.ASFT,
HSHT = d1.HSHT,
ASHT = d1.ASHT,
HSSH = d1.HSSH,
ASSH = d1.ASSH,
HODD = d2.HODD,
XODD = d2.XODD,
AODD = d2.AODD,
RisFin = d2.RisFin,
Over05SH = d2.Over05SH
};
var combinedDataList = (from d1 in dataList1
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in dataList2 on new { d1.Home, d1.Away } equals new { d2.Home, d2.Away }
select new CombinedData
{
Campionato = d1.Campionato,
Data = d1.Data,
Home = d2.Home,
Away = d2.Away,
HSFT = d1.HSFT,
ASFT = d1.ASFT,
HSHT = d1.HSHT,
ASHT = d1.ASHT,
HSSH = d1.HSSH,
ASSH = d1.ASSH,
HODD = d2.HODD,
XODD = d2.XODD,
AODD = d2.AODD,
RisFin = d2.RisFin,
Over05SH = d2.Over05SH
}).OrderBy(p=>p.HODD);
please try

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS

what is the wrong with this LINQ statement:
(from deposit in DAOBase<CashBookDeposit, long>.GetIQueryableBusinessBase()
where deposit.Id == id
select new CashBookDeposit
{
Id = deposit.Id,
DepositeNumber = deposit.DepositeNumber,
DocumentTypeName = deposit.CashBookDepositDocumentType.EnglishName,
StatusName = deposit.CashBookDepositeStatus.EnglishName,
CashbookName = deposit.CashBook.EnglishName,
Collector = deposit.Collector,
Partner = deposit.Partner,
CashBookDepositDocumentType = deposit.CashBookDepositDocumentType,
CreationDate = deposit.CreationDate,
PaidAmount = deposit.TotalAmount,
Description = deposit.Description,
TempReceipts = (from receipt in deposit.TempReceipts
select new TempReceipt
{
Id = receipt.Id,
Code = receipt.Code,
ReceiptNo = receipt.ReceiptNo,
Amount = receipt.Amount,
BusinessPartnerName = receipt.Partner.ENName,
CollectorName = receipt.Collector.EnglishName,
StatusName = receipt.TempReceiptStatus.EnglishName,
CollectionDate = receipt.CollectionDate,
CreationDate = receipt.CreationDate,
Description = receipt.Description,
}).ToList()
}).SingleOrDefault();
i got this exception :
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
need help, thanks
You can change the query as follows:
(from deposit in DAOBase<CashBookDeposit, long>.GetIQueryableBusinessBase()
let receipts = (from tempReceipts in deposit.TempReceipts
select tempReceipts)
where deposit.Id == id
select new CashBookDeposit
{
Id = deposit.Id,
DepositeNumber = deposit.DepositeNumber,
DocumentTypeName = deposit.CashBookDepositDocumentType.EnglishName,
StatusName = deposit.CashBookDepositeStatus.EnglishName,
CashbookName = deposit.CashBook.EnglishName,
Collector = deposit.Collector,
Partner = deposit.Partner,
CashBookDepositDocumentType = deposit.CashBookDepositDocumentType,
CreationDate = deposit.CreationDate,
PaidAmount = deposit.TotalAmount,
Description = deposit.Description,
TempReceipts = (from receipt in receipts
select new TempReceipt
{
Id = receipt.Id,
Code = receipt.Code,
ReceiptNo = receipt.ReceiptNo,
Amount = receipt.Amount,
BusinessPartnerName = receipt.Partner.ENName,
CollectorName = receipt.Collector.EnglishName,
StatusName = receipt.TempReceiptStatus.EnglishName,
CollectionDate = receipt.CollectionDate,
CreationDate = receipt.CreationDate,
Description = receipt.Description,
}).ToList()
}).SingleOrDefault();

Categories