linq group by id and sum of amount getting null(undefined) - c#

var approverlist = _db.ApprvRejClaimTravelCashByApproverIdIPhone(ProjectSession.CompanyUserId, ProjectSession.CompanyId, Status).AsEnumerable().ToList();`
var results =
from item in approverlist
group item by item.ClaimId
into g
select new
{
ClaimId = g.Key,
Name = g.First().Name,
Amount = g.Sum(s => s.Amount),
Description = g.First().Description,
Status = g.First().Status,
CreatedDate = g.First().CreatedDate,
SubmitedDate = g.First().SubmitedDate,
FullName = g.First().FullName,
ApproverStatus = g.First().ApproverStatus,
CurrencySymbol = g.First().CurrencySymbol,
chkbox = g.First().chkbox,
IsHierarchy = g.First().IsHierarchy,
ColumnCategory = g.First().ColumnCategory,
ColumnCategoryCode = g.First().ColumnCategoryCode
};
return Json(results.ToDataSourceResult(request));
getting undefined in column Amount when i bind this result to my kendo mvc grid,,,,any one have idea why this happens ?
Also tried below one but same result undefined :
var results = from x in approverlist
group x.ClaimId by new { x.ClaimId, x.Name, x.Description, x.Status, x.CreatedDate, x.SubmitedDate, x.FullName, x.ApproverStatus, x.CurrencySymbol, x.chkbox, x.IsHierarchy, x.ColumnCategory, x.ColumnCategoryCode }
into g
select new { g.Key.ClaimId, g.Key.Name, Amount = g.Sum(), g.Key.Description, g.Key.Status, g.Key.CreatedDate, g.Key.SubmitedDate, g.Key.FullName, g.Key.ApproverStatus, g.Key.CurrencySymbol, g.Key.chkbox, g.Key.IsHierarchy, g.Key.ColumnCategory, g.Key.ColumnCategoryCode };

Related

Entity Framework Core - (Kind of subquery)

I use fluent API and Ef Core.
This is my linq:
var data = (from candidateHP in _cempContexto.CandidateHiringProcessSummary
join jobsHP in _cempContexto.JobHiringProcessSummary on candidateHP.JobCode equals jobsHP.JobCode
join job in _cempContexto.Vaga on jobsHP.JobCode equals job.Codigo
join candidateJob in _cempContexto.TrCandidatoVaga on new { X = job.Codigo, Y = candidateCode } equals new { X = candidateJob.VagaCodigo, Y = candidateJob.CandidatoCodigo }
where
candidateHP.CandidateCode == candidateCode
select
new
{
JobCode = jobsHP.JobCode,
CompanyCode = job.EmpresaCodigo,
Title = job.Titulo,
HasImage = true,
CompanyName = job.NomeEmpresa,
QuantityJobs = job.QuantidadeVaga,
Location = job.CidadeCodigo,
QuantityResumeSent = jobsHP.QuantityResumeSent,
JobStatusCode = jobsHP.StatusCode,
CandidateStatusCode = candidateHP.StatusCode,
StatusCode = job.StatusCodigo,
ResumeSentDate = candidateJob.Data,
InsertDate = job.DataDeCadastro,
EndDate = job.DataDeSaida,
city= _cempContexto.TrVagaCidade.SelectMany(p => _cempContexto.TrVagaCidade.Where(q => q.VagaCodigo == candidateHP.JobCode).Select(q => new { q })).ToList()
})
.ToList();
I need to Fill city with that subquery. I need a better way to do that, How could I proceed?
Split code into two queries :
var query = (from candidateHP in _cempContexto.CandidateHiringProcessSummary
join jobsHP in _cempContexto.JobHiringProcessSummary on candidateHP.JobCode equals jobsHP.JobCode
join job in _cempContexto.Vaga on jobsHP.JobCode equals job.Codigo
join candidateJob in _cempContexto.TrCandidatoVaga on new { X = job.Codigo, Y = candidateCode } equals new { X = candidateJob.VagaCodigo, Y = candidateJob.CandidatoCodigo }
where
candidateHP.CandidateCode == candidateCode
select
new
{ jobsHP = jobsHP, job = job, candidateJob = candidateJob}).ToList();
var data = query.Select(x => new {
JobCode = x.jobsHP.JobCode,
CompanyCode = x.job.EmpresaCodigo,
Title = x.job.Titulo,
HasImage = true,
CompanyName = x.job.NomeEmpresa,
QuantityJobs = x.job.QuantidadeVaga,
Location = x.job.CidadeCodigo,
QuantityResumeSent = x.jobsHP.QuantityResumeSent,
JobStatusCode = x.jobsHP.StatusCode,
CandidateStatusCode = x.candidateHP.StatusCode,
StatusCode = x.job.StatusCodigo,
ResumeSentDate = x.candidateJob.Data,
InsertDate = x.job.DataDeCadastro,
EndDate = x.job.DataDeSaida,
city= query.Select(y => y.candidateHP.JobCode).Select(q => new { q })).ToList()
})
.ToList();

Linq-OrderByDescending doesn't work for me-ASP.net MVC

I want to order my list by idEtatD but this attribute isn't my table primarykey or id it's a normal attribute migrated from another table,nut OrderBy or OrderByDescending didn't give me a result my list still not ordered by idEtatD.
public ActionResult ListeDemande( int? page)
{
traçabilitérepository=new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
select new
{
id_demande=d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});
int pageSize = 10;
int pageNumber = (page ?? 1);
return View(listdemandes.OrderByDescending(x => x.idEtatD).ToList().ToPagedList(pageNumber, pageSize));
}
Please I need your help and thank you.
You can order the items at the beginning, but you need to include it in the list:
traçabilitérepository = new TraçabilitéDemandeRepository(db);
var listdemandes = (from d in db.Demande_Gabarit
join t in db.Traçabilité_Demande_Gabarit
on d.id_demande equals t.iddemande into ThisList
from t in ThisList.DefaultIfEmpty()
orderby t.idEtatD descending
select new
{
id_demande = d.id_demande,
NumDemande = d.NumDemande,
Emetteur = d.Emetteur,
Date = d.Date,
Ligne = d.Ligne.designation,
Etat = t.Etat_Demande_Gabarit.EtatDemande,
idEtatD = XXXX
}).ToList().Select(x => new DemandeViewModel()
{
NumDemande = x.NumDemande,
Emetteur = x.Emetteur,
Date = x.Date,
designation = x.Ligne,
EtatDemande = x.Etat,
id_demande = x.id_demande
});

LINQ not sorting List<> properly

My EF query is supposed to be sorting by the date of the first Product in the list, but for some reason, it only sorts most of the products and some of the dates are in the wrong order.
Here's the code...
using (var context = new SalesEntities())
{
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID, c.s84_Customer.CustomerName, c.SubdivisionID, c.s84_Subdivision.SubdivisionName, c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).ToList()
});
var finalList = groupedData.ToList().Where(x => x.Products.Last().Completed == false).ToList();
List<s84_Report_Project_POCO> lst = finalList.OrderBy(x => x.Products.First().ProductDate).ToList();
return lst;
}
Code seems good to me, but look at how one of the dates is out of order...
weird sorting http://www.84sales.com/weird_sort.png
Try doing the order by on the inital select
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID,
c.s84_Customer.CustomerName,
c.SubdivisionID,
c.s84_Subdivision.SubdivisionName,
c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped
.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).OrderBy(x => x.CustomerExpectedDate).ToList()
});
The problem is the .First() function, witch returns the first record, but not necessarly in date order. if you wich to order your grouped datas by date so that the First() function returns the most recent date, you'll need to order your datas before grouping them, and then REorder your results with the First()function :
using (var context = PrimaryConnection.returnNewConnection())
{
var groupedData = context.s84_Schedule.AsExpandable()
.Where(predicate)
.GroupBy(c => new { c.CustomerID, c.s84_Customer.CustomerName, c.SubdivisionID, c.s84_Subdivision.SubdivisionName, c.LotNumber })
.Select(grouped => new s84_Report_Project_POCO
{
CustomerID = grouped.Key.CustomerID,
CustomerName = grouped.Key.CustomerName,
SubdivisionID = grouped.Key.SubdivisionID,
SubdivisionName = grouped.Key.SubdivisionName,
LotNumber = grouped.Key.LotNumber,
Products = grouped
.Select(x => new s84_Report_Project_Product
{
ProductID = x.ProductID,
ProductName = x.s84_Product.ProductName,
ProductDate = x.CustomerExpectedDate,
FieldRepID = x.FieldRepID,
FieldRepName = x.s84_FieldRep.FieldRepName,
InstallerID = x.InstallerID,
InstallerName = x.s84_Installer.InstallerName,
StatusID = x.StatusID,
StatusColor = x.s84_Status.StatusColor,
StatusName = x.s84_Status.StatusName,
Completed = x.Completed
}).Orderby(t => t.CustomerExpectedDate).ToList()
});
var finalList = groupedData.ToList().Where(x => x.Products.Last().Completed == false).ToList();
List<s84_Report_Project_POCO> lst = finalList.OrderBy(x => x.Products.First().ProductDate).ToList();
All SQL queries (and hence Linq queries, when attached to a SQL database) have a random order, unless you sort them.
Products is not sorted - hence it has a random order.
You sort by Products.First(), but Products has a random order, so your sort will also be random.
Make sure Products is sorted within the query, and you should be ok.
Products = grouped.Select(....)
.OrderBy(x => x.ProductDate)
.ToList()

How can I use this Linq Query using it with a multiple parameter by Join tables

var list = dc.Orders.
Join(dc.Order_Details,
o => o.OrderID, od => od.OrderID, <-- what if i have 2 more parameters let say an ID and a REC on both table. ex.: o=> o.OrderID && o.ItemName, od => od.OrderID && od.Itemname then (o, od) but its result is error? is there another way?
(o, od) => new
{
OrderID = o.OrderID,
OrderDate = o.OrderDate,
ShipName = o.ShipName,
Quantity = od.Quantity,
UnitPrice = od.UnitPrice,
ProductID = od.ProductID
}).Join(dc.Products,
a => a.ProductID, p => p.ProductID, <-- at this point too?
(a, p) => new
{
OrderID = a.OrderID,
OrderDate = a.OrderDate,
ShipName = a.ShipName,
Quantity = a.Quantity,
UnitPrice = a.UnitPrice,
ProductName = p.ProductName
});
is it possible to use this lambda expression linq query with multiple parameters by joining 3 tables?
--- UPDATE STILL ERROR -- :(
var header = DB.Delivery_HeaderRECs.Join(DB.Delivery_DetailsRECs, <-- Red Line on DB.Delivery_HeaderRECs.Join
q => new { q.drNO, q.RecNO },
qw => new { qw.DrNO, qw.RecNO },
(q, qw) => new
{
DR = q.drNO,
DATE = q.DocDate,
RECNO = q.RecNO,
CUSTID = q.CustomerID,
CUSTADDR = q.CustomerADDR,
RELEASE = q.ReleasedBy,
RECEIVE = q.ReceivedBy,
REMARKS = q.Remarks,
ITEM = qw.ItemCode,
DESC = qw.ItemDesc,
QTY = qw.Qty,
COST = qw.Unit,
PLATENO = qw.PlateNo,
TICKETNO = qw.TicketNo
}).Join(DB.Delivery_TruckScaleRECs,
w => new { w.DR, w.TICKETNO },
we => new { we.DrNo, we.TicketNO },
(w, we) => new
{
DR = w.DR,
DATE = w.DATE,
RECNO = w.RECNO,
CUSTID = w.CUSTID,
CUSTADDR = w.CUSTADDR,
RELEASE = w.RELEASE,
RECEIVE = w.RECEIVE,
REMARKS = w.REMARKS,
ITEM = w.ITEM,
DESC = w.DESC,
QTY = w.QTY,
COST = w.COST,
PLATENO = w.PLATENO,
TICKETNO = w.TICKETNO,
TRANSAC = we.TransactionType,
FWEIGHT = we.FirstWeight,
SWEIGHT = we.SecondWeight,
NWEIGHT = we.NetWeight
}).FirstOrDefault();
I made up changes base on the answer but an error said above the statement:
"The type arguments for method cannot be inferred from the usage. Try specifying the type arguments explicitly". i think it's talking about the parameters i've made..
You can use anonymous type for the Join like this:
var list = dc.Orders.Join(dc.Order_Details,
o => new { o.OrderID, o.ItemName},
od => new { od.OrderID, od.ItemName},
...);
The anonymous type will be compiled to use the autoimplemented Equals and GetHashCode so that the equality will be derived by the equality of all the corresponding properties. Just add more properties as you want in the the new {....}. Note that the order of properties provided in the 2 new {...} should be the same order of correspondence. The names should also be matched, you can explicitly specify the names to ensure this (this is needed in some cases) such as:
new {OrderID = o.OrderID, Name = o.ItemName}
However in your case the property names will be used as the same properties of the item.
UPDATE
This update is just a fix for your specific parameters, I said that the property names should be the same, if they are not you have to explicitly name them like this:
var list = dc.Orders.Join(dc.Order_Details,
q => new {DrNO = q.drNO, q.RecNO},
qw => new {DrNO = qw.DrNO, qw.RecNO},
...);

Grouping in linq

I have a following list of documents:
List<DocumentInfo> list1 = new List<DocumentInfo>()
{
new DocumentInfo { Name = "Customer1", DocCount = 5 },
new DocumentInfo { Name = "Customer1", DocCount = 10 },
new DocumentInfo { Name = "Customer1", DocCount = 5 },
new DocumentInfo { Name = "Customer2", DocCount = 4 },
new DocumentInfo { Name = "Customer2", DocCount = 6 },
new DocumentInfo { Name = "Customer3", DocCount = 3 }
};
How to group the above list based on 'Name' and sum of 'DocCount' using Linq and store in another list? I want something like following:
Name = "Customer1", DocCount = 20
Name = "Customer2", DocCount = 10
Name = "Customer3", DocCount = 3
var results = list1.GroupBy(i => i.Name)
.Select(g => new
{
Name = g.Key,
DocCount = g.Sum(i => i.DocCount)
});
var list2 = list1.GroupBy(x => x.Name).Select(g => new DocumentInfo()
{
Name = g.Key,
DocCount = g.Sum(x => x.DocCount)
});
Try this:
list1.GroupBy(di => di.Name).Select(g => new DocumentInfo {Name = g.Key, DocCount = g.Sum(dc => dc.DocCount)});
var result= from item in list1
group item by item.Name
into g
select g;
var groupedInfo = result.SelectMany(group => group);
foreach(var g in groupedInfo)
{
//Do Summation
}
Try like this;
var anotherlist = list1.GroupBy(g => g.Name)
.Select(s => new
{
Name = s.Key,
DocCount = s.Sum(i => i.DocCount)
});
It is simply, getting sum of DocCount and their Name properties by grouping based Name.
Here is another way to do the same
var sumOfDocs = from doc in list1 group doc by doc.Name into g
select new { DocName = g.Key, DocSum = g.Sum(i => i.DocCount) };

Categories

Resources