Not getting the difference between two list by using linq - c#

I have two lists as follows:
var SeparatedEmployees = (from s in DataContext.HRM_EMP_TRMN.AsEnumerable()
where s.TRMN_FINL_STUS == "SA" && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(s.TRMN_EFCT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on s.EMP_CODE equals e.EMP_CODE
where e.ACTIVE_STATUS == "A"
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
var ConfirmedEmployees = (from c in DataContext.HRM_EMP_FINL_STMT_MST.AsEnumerable()
where ((Convert.ToDateTime(c.FINL_STMT_DATE)).Year).ToString() == Year && ((Convert.ToDateTime(c.FINL_STMT_DATE)).Month).ToString() == HRMD_COMMON.ReturnMonthName(Month)
join e in DataContext.VW_HRM_EMPLOYEE on c.EMP_CODE equals e.EMP_CODE
join s in DataContext.HRM_EMP_TRMN on c.EMP_CODE equals s.EMP_CODE
select new HRM_EMP_FINL_STMT_MSTModel
{
EMP_CODE = s.EMP_CODE,
EMP_NAME = e.EMP_NAME,
DIVI_CODE = e.DIVI_CODE,
DIVI_NAME = e.DIVI_NAME,
EMP_DESIG_CODE = e.EMP_DESIG_CODE,
EMP_DESIG_NAME = e.EMP_DESIG_NAME,
JOINING_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(e.JOINING_DATE)),
TRMN_TYPE = HRMD_COMMON.ReturnTerminationType(s.TRMN_TYPE),
TRMN_EFCT_DATE = HRMD_COMMON.ReturnOnlyDate(Convert.ToDateTime(s.TRMN_EFCT_DATE)),
LAST_SAL_PROS_MON = HRMD_COMMON.ReturnMonthName(s.LAST_SAL_PROS_MON),
FINL_STMT_REM = s.TRMN_REM
}).ToList();
Tyring to remove the items from the first list, which are also in second list.
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ConfirmedEmployees.Contains(item)
select item).ToList();
Tried this one too:
FinalSeparatedEmployees = SeparatedEmployees.Except(ConfirmedEmployees).ToList<HRM_EMP_FINL_STMT_MSTModel>();
But not getting the accurate result. What I'm missing? Thanks.

Its better to use EMP_CODE because your objects are not comparable.
var ids = ConfirmedEmployees.Select(x => x.EMP_CODE).ToList();
var FinalSeparatedEmployees = (from item in SeparatedEmployees
where !ids.Contains(item.EMP_CODE)
select item).ToList();

Related

Include Newest Note and Comment in List

I have to include both the newest Note and Comment with view model that I am passing to my list view but I cannot figure out how to include it in the view model.
I tried to do include but after I type p it will not give me a list of my properties for MinimumProductInfo which ProductNotes is a property for it.
Here is the controller code I am trying:
public ActionResult MinimumProductInfoList()
{
var Model = _minimumProductInfo.GetAll();
var Notes = db.ProductNotes.Where(p => p.NoteTypeFlag == "p").OrderByDescending(p => p.NoteDate).First();
var Comments = db.ProductNotes.Where(p => p.NoteTypeFlag == "c").OrderByDescending(p => p.NoteDate).First();
var Model = db.MinimumProductInfo.Include(p => p)
var ViewModel = Model.Select(x => new ProductInfoWithNoteList { MinimumProductInfoID = x.MinimumProductInfoID, ItemCode = x.ItemCode, MinimumOnHandQuantity = x.MinimumOnHandQuantity, MaximumOHandQuantity = x.MaximumOHandQuantity, MinimumOrderQuantity = x.MinimumOrderQuantity, LeadTimeInWeeks = x.LeadTimeInWeeks });
return View(ViewModel);
}
Everything else is working except now I need to include the latest note and latest comment in to my viewmodel
This is what I have now with WithMetta's help:
public ActionResult MinimumProductInfoList()
{
var productInfoViewModelCollection =
from x in db.MinimumProductInfo
let pnote =
(from inner_pnote in db.ProductNotes
where x.MinimumProductInfoID == inner_pnote.MinimumProductInfoID
&& inner_pnote.NoteTypeFlag == "p"
orderby inner_pnote.NoteDate
select inner_pnote).FirstOrDefault()
let cnote =
(from inner_cnote in db.ProductNotes
where x.MinimumProductInfoID == inner_cnote.MinimumProductInfoID
&& inner_cnote.NoteTypeFlag == "c"
orderby inner_cnote.NoteDate
select inner_cnote).FirstOrDefault()
select new ProductInfoWithNoteList
{
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Comment = cnote.ToString(),
PermanentNote = pnote.ToString()
};
return View(productInfoViewModelCollection);
}
Maybe something like this using LINQ.
var productInfoViewModelCollection =
from x in db.MinimumProductInfo
where x != null
let pnote =
(from inner_pnote in db.ProductNotes
where inner_pnote != null
&& x.MinimumProductInfoID == inner_pnote.MinimumProductInfoID
&& inner_pnote.NoteTypeFlag == "p"
orderby inner_pnote.NoteDate descending
select inner_pnote).FirstOrDefault()
let cnote =
(from inner_cnote db.ProductNotes
where inner_cnote != null
&& x.MinimumProductInfoID == inner_cnote.MinimumProductInfoID
&& inner_cnote.NoteTypeFlag == "c"
orderby inner_cnote.NoteDate descending
select inner_cnote).FirstOrDefault()
select new ProductInfoWithNoteList {
MinimumProductInfoID = x.MinimumProductInfoID,
ItemCode = x.ItemCode,
MinimumOnHandQuantity = x.MinimumOnHandQuantity,
MaximumOHandQuantity = x.MaximumOHandQuantity,
MinimumOrderQuantity = x.MinimumOrderQuantity,
LeadTimeInWeeks = x.LeadTimeInWeeks,
Comment = cnote,
PermanentNote = pnote
};

How to merge if row in table exists

I have a 3 tables joined in the statement below:
var data = from x in dbContext.Base_Agencies
from u in dbContext.Base_AgencyInstances
from o in dbContext.Payment2Account_SecurityRuleAgencies
where u.AgencyId == x.AgencyId
where o.AgencyId == x.AgencyId
where u.AgencyInstanceId == param.AgencyInstanceId
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = o.ServiceEnabled,
DisabledDateTime = o.DisabledDateTime,
AmountHourTresholdWarning = o.AmountHourTresholdWarning,
AmountHourTresholdStop = o.AmountHourTresholdStop,
CountHourTresholdWarning = o.CountHourTresholdWarning,
CountHourTresholdStop = o.CountHourTresholdStop
};
The problem is that in some examples there won't be a row for agency in table 'o'. In this situation I would like to select values only from other tables, except 'o' table. How should I do that?
I think you might want to do a LEFT OUTER JOIN like
var data = from x in dbContext.Base_Agencies
join u in dbContext.Base_AgencyInstances
on u.AgencyId == x.AgencyId
join o in dbContext.Payment2Account_SecurityRuleAgencies
on o.AgencyId == x.AgencyId into lrs
from lr in lrs.DefaultIfEmpty()
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = lr.ServiceEnabled ?? "Default",
...... // other code similar ........
};
Correct solution is:
var data = from x in dbContext.Base_Agencies
join u in dbContext.Base_AgencyInstances
on x.AgencyId equals u.AgencyId
join o in dbContext.Payment2Account_SecurityRuleAgencies
on x.AgencyId equals o.AgencyId into lrs
from lr in lrs.DefaultIfEmpty()
where u.AgencyInstanceId == param.AgencyInstanceId
select new RsSecurityParamsResult
{
AgencyId = x.AgencyId,
AgencyNameView = u.AgencyNameView,
Stamp = u.Stamp,
Pni = x.Pni,
Prefix = u.Prefix,
ServiceEnabled = lr.ServiceEnabled,
DisabledDateTime = lr.DisabledDateTime,
AmountHourTresholdWarning = lr.AmountHourTresholdWarning ,
AmountHourTresholdStop = lr.AmountHourTresholdStop,
CountHourTresholdWarning = lr.CountHourTresholdWarning ,
CountHourTresholdStop = lr.CountHourTresholdStop
};

C# - LINQ - Sum a field from other table

I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto
Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.
This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group ct by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum(mov.Monto)
}
).ToList();
You need to group the value you want to sum like this
group mov.Monto by new { ..... } into ctg
Then ctg will be a collection of mov.Monto values grouped by your list of properties of ct and you'd just call Sum on ctg in your select
Monto = ctg.Sum()
So your new query would be
var cuentas = (from mov in _data.Movimientos
join ct in _data.Cuentas
on mov.CuentasId equals ct.CuentasId
where ct.IsDeleted == 0 && mov.IsDeleted == 0
group mov.Monto by new
{
CuentasId = ct.CuentasId,
Alias = ct.Alias,
Moneda = ct.Monedas.Nombre,
Signo = ct.Monedas.Signo,
Banco = ct.Bancos.Nombre
} into ctg
select new
{
Alias = ctg.Key.Alias,
Moneda = ctg.Key.Moneda,
Signo = ctg.Key.Signo,
Banco = ctg.Key.Banco,
Monto = ctg.Sum()
}).ToList();
You could also try grouping by first and then just summing the items later:
var cuentas = (from mov in _data.Movimientos.Where(w => w.IsDeleted == 0).GroupBy(g => g.CuentasId)
join ct in _data.Cuentas.Where(w => w.IsDeleted == 0).GroupBy(g => new { CuentasId = g.CuentasId, Alias = g.Alias, Monedas = g.Monedas.Nombre, Signo = g.Monedas.Signo, Banco = g.Bancos.Nombre })
on mov.Key.CuentasId equals ct.Key.CuentasId
select new
{
Alias = ct.Key.Alias,
Moneda = ct.Key.Moneda,
Signo = ct.Key.Signo,
Banco = ct.Key.Banco,
Monto = mov.Sum(s => s.Monto)
}
).ToList();

Join LINQ with a List<> in select new

hi first time im asking here so il try to do it correctly
i have a problem im making a shopping basket and im nearly there but always a but
what i want to have is something like this
List<HKurv> KurvInnhold = (List<HKurv>)Session["KurvInnhold"];
DataClasses1DataContext db = new DataClasses1DataContext();
if (Session["KurvInnhold"] != null)
{
var query = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
d.VareKjøpt.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
BestiltAntall = d.AntallValgt,
Price = b.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query;
Handlekurv1.DataBind();
}
But it does not allow for usage of db and list<> in same query
Solved! Modified magnus's answer
var kjopKollonne = from p in KurvInnhold
select p.VareKjøpt;
var query1 = (from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
where
kjopKollonne.Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}).ToList();
var query2 = from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();
Try this:
var query1 = from a in db.Cabinets
from b in db.Commodities
from e in db.sArticleNumbers
from d in KurvInnhold
where
KurvInnhold.Select(k => k.VareKjøpt).Contains(e.ArtNum) &&
a.ArticleNumberID == e.ID &&
a.ArticleNumberID == b.ArticleNumberID
select new
{
ArtNum = e.ArtNum,
Price = b.Price,
ModelName = a.ModelName,
}.ToList();
var query2 =
from a in query1
join b in KurvInnhold on a.ArtNum equals b.VareKjøpt
select new
{
BestiltAntall = b.AntallValgt,
Price = a.Price,
ModelName = a.ModelName,
};
Handlekurv1.DataSource = query2;
Handlekurv1.DataBind();

Call Method from Linq query

I am using Linq query and call method Like..
oPwd = objDecryptor.DecryptIt((c.Password.ToString())
it will return null value.
Means this will not working.
how I Resolve this.
Thanks..
var q =
from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings
on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = objDecryptor.DecryptIt(c.Password.ToString()),
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
If that is LINQ-to-SQL or Entity Framework. You'll need to break it into steps (as it can't execute that at the DB). For example:
var q = from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = c.Password,
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
then use AsEnumerable() to break "composition" against the back-end store:
var query2 = from row in q.AsEnumerable()
select new
{
row.oUserId,
row.oUserName,
row.oEmailId,
row.oEmailAccId,
oPwd = objDecryptor.DecryptIt(row.oPwd),
row.oServerName,
row.oServerAdd,
row.oPOPSettingId
};
var q = from s in db.User
join c in db.EmailAccount on s.UserId equals c.UserId
join d in db.POPSettings on c.PopSettingId equals d.POPSettingsId
where s.UserId == UserId && c.EmailId == EmailId
select new
{
oUserId = s.UserId,
oUserName = s.Name,
oEmailId = c.EmailId,
oEmailAccId = c.EmailAccId,
oPwd = c.Password,
oServerName = d.ServerName,
oServerAdd = d.ServerAddress,
oPOPSettingId = d.POPSettingsId,
};
foreach (var item in q)
{
item.oPwd = objDecryptor.DecryptIt(row.oPwd),
}
we can use a foreach loop also to update a single property. do not need to select all property in next query.
This has nothing about Linq query. you need to debug method objDecryptor.DecryptIt

Categories