How to select Max StartDate in Linq - c#

I want to only get out the max StartDate, its multiples of dates with the same CustomNumber
Any suggestions?
My simplified code
from Cus in Customers
where Cus.CustomNumber == 2
group Cus by new
{ Cus.Name,Cus.City,Cus.StartDate}
into grp
select new
{
Name = grp.Key.Name,
City = grp.Key.City,
StartDate = grp.Key.StartDate,
//I have tried, but it doesnt work for me
//StartDate = grp.Max(Cus=> grp.Key.StartDate)
}

try below code
StartDate = grp.Max(x => x.StartDate)

You could try this one:
var result = from Cus in Customers
where Cus.CustomNumber == 2
group Cus by new
{ Cus.Name, Cus.StartDate}
into grp
select new
{
Name = grp.Key.Name,
StartDate = grp.Max(x=>x.StartDate)
};
Using grp you have access to the random group you create in your linq query, then using the extension method called Max you get the maximum StartDate in your group.
UPDATE
Since now you have a join before the grouping, you have to change your code to the following one:
var result = from res in
(from customer in Customers
join house in Houses
on customer.CustomNumber equals house.CustomNumber
where customer.CustomNumber == 2
select new { Name = customer.Name, StartDate = house.StartDate })
group res by res.Name into grp
select new { Name = grp.Key, StartDate = grp.Max(x=>x.StartDate) };
UPDATE #2
If you want you get both the customer's Name and City in your result, you have to use the following code:
var result = from res in
(from customer in Customers
join house in Houses
on customer.CustomNumber equals house.CustomNumber
where customer.CustomNumber == 2
select new { Name = customer.Name, City = customer.Name, StartDate = house.StartDate })
group res by new { res.Name, res.City } into grp
select new
{
Name = grp.Key.Name,
City = grp.Key.City,
StartDate = grp.Max(x=>x.StartDate)
};

Related

Join with order by in Entity - but need only last date for the Closed Balance

i am looking for help to join 3 tables but from the last table
I only need the last entry by date for the balance. I tried OrderByDescending
for the GLBalances table .
var list = await (from ba in _context.BankAccounts
join bnk in _context.Banks on ba.BankId equals bnk.ID
join glB in _context.GLBalances on ba.BankGL equals glB.GLAccountGuid
select new BankAccountDto()
{
BankId = ba.BankId,
AccountNumber = ba.AccountNumber,
BankName = bnk.BankName,
Notes = ba.Notes,
Description = ba.Description,
Balance = (decimal)glB.ClosingBalance // ***need the last entry by date
}).ToListAsync();
To get the last entry by date for the GLBalances table, you can use the OrderByDescending method to sort the GLBalances records by date in descending order. Am assuming here column name is Date
You can modify your query to achieve this:
var list = await (from ba in _context.BankAccounts
join bnk in _context.Banks on ba.BankId equals bnk.ID
join glB in _context.GLBalances
.OrderByDescending(glb => glb.Date)
.Where(glb => glb.GLAccountGuid == ba.BankGL)
.Take(1) on ba.BankGL equals glB.GLAccountGuid
select new BankAccountDto()
{
BankId = ba.BankId,
AccountNumber = ba.AccountNumber,
BankName = bnk.BankName,
Notes = ba.Notes,
Description = ba.Description,
Balance = (decimal)glB.ClosingBalance
}).ToListAsync();
Updated. try this,
var list = await (from ba in _context.BankAccounts
join bnk in _context.Banks on ba.BankId equals bnk.ID
join glB in _context.GLBalances.OrderByDescending(glb => glb.EndDate).Take(1)
on ba.BankGL equals glB.GLAccountGuid
where glB.GLAccountGuid == ba.BankGL
select new BankAccountDto()
{
BankId = ba.BankId,
AccountNumber = ba.AccountNumber,
BankName = bnk.BankName,
Notes = ba.Notes,
Description = ba.Description,
Balance = (decimal)glB.ClosingBalance
}).ToListAsync();

Select Distinct from multiple tables linq to sql

I have tow tables, tblItem and tblInsertLines, in tblInsertLines I have the same ItemId but with differnt ProdDate and ExpireDate, I want to get a distinct list of all items but select the first row from tblInsertLines as the first row contains the oldest ProdDate.
Any help will be appreciated. I use this code.
public static List<Item> getItemList()
{
using (var db = new AWarehouseDataClassesDataContext())
{
var list = (from i in db.tblItems
join e in db.tblInsertLines on i.ItemId equals e.ItemId
orderby i.NameE
select new Item
{
code = i.Code,
itemId = i.ItemId,
lastUpdate = i.LastUpdate,
nameA = i.NameA,
nameE = i.NameE,
qty = i.Qty,
prodDate = e.ProdDate,
expireDate = e.ExpireDate,
updatedBy = i.UpdatedBy
}).Distinct();
return list.ToList();
}
}
You can try
var list= (from i in db.tblItems
join e in db.tblInsertLines on i.ItemId equals e.ItemId
where e.counter > 0
orderby i.NameE
group new { i, e } by e.ItemId into g
select new Item
{
code = g.First().i.Code,
itemId = g.Key,
lastUpdate = g.First().i.LastUpdate,
nameA = g.First().i.NameA,
nameE = g.First().i.NameE,
qty = g.First().i.Qty,
prodDate = g.Min(x=>x.e.ProdDate),
expireDate = g.First().e.ExpireDate,
updatedBy = g.First().i.UpdatedBy
}).ToList();

Getting a field value from a LINQ query without Iteration

I have the following query in controller and I want to store a column value in a variable but I am not being able to iterate it. Here is my code:
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Status equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where(SRMAs.Id == srmaid)
group SRMADetails by new
{
SRMADetails.Id,
SRMADetails.SRMAId,
SRMADetails.SupplierPartNum,
SRMAs.PONumber,
SRMAs.ActualAmount,
SRMAs.ApprovedOn,
SRMAs.Status,
SRMAs.TrackingNumber,
SRMAs.SupplierRMANumber,
SRMAs.RequestedFromSupp,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate,
PurchaseOrders.suppliersOrderNumber
} into grp
select new
{
grp.Key.Status,
grp.Key.SRMAId,
grp.Key.Id,
grp.Key.PONumber,
grp.Key.SupplierRMANumber,
grp.Key.ActualAmount,
grp.Key.SupplierPartNum,
grp.Key.RequestedFromSupp,
grp.Key.TrackingNumber,
grp.Key.ApprovedOn,
grp.Key.SupplierName,
grp.Key.StatusName,
grp.Key.PODate,
grp.Key.suppliersOrderNumber,
grp.Key.CreatedOn,
Sum = grp.Sum(SRMADetails => SRMADetails.Cost * SRMADetails.QtyReturned)
}
).ToList();
System.Collections.IEnumerable et = (System.Collections.IEnumerable)srmas;
IEnumerator it = et.GetEnumerator();
while (it.MoveNext())
{
SRMA current = (SRMA)it.Current;
Response.Write(current.Status);
}
ViewBag.SRMAs = srmas.Select(srma => new IndexViewModel
{
Id = srma.SRMAId,
SupplierRMANum = srma.SupplierRMANumber,
SRMADetailsID = srma.Id,
PONumber = srma.PONumber,
CreatedOn = srma.CreatedOn,
SupplierName = srma.SupplierName,
SRMAStatus = srma.StatusName,
Status = srma.Status,
suppliersOrderNumber = srma.suppliersOrderNumber,
PODate = srma.PODate,
Sum = srma.Sum,
TrackingNumber = srma.TrackingNumber,
ActualAmount = srma.ActualAmount
}).ToList();
I just want to get Status value of first record. How do I do it?

Select a field that is not in Group By clause in LINQ

could anybody help me about
"How to select a field that is not in Group By clause in LINQ"
var ReportData =
from a in context.Table1
from b in context.Table2
where a.personelID == b.ID
&& a.DateField.Value.Year == 2011
group a by new { a.personelID, b.Name, b.Surname} into grouping
select new
{
// grouping.Key.DateField,
Name= grouping.Key.Name,
Surname= grouping.Key.Surname,
PagaBruto = grouping.Sum(i => i.Bruto)),
};
I can't select the field "DateField" that is in Table1, I don't want to have this field in Group By, because I will get a wrong result.
THANKS!
I think you need to select both table members before you group by so you can select data from both. I did a join instead of your where clause.
(from a in context.Table1
join b in context.Table2 on a.PersonalID equals b.ID
select new { A=a, B=b } into joined
group joined by new { joined.A.PersonalID, joined.B.Name, joined.B.Surname } into grouped
select grouped.Select(g => new {
DateField= g.A.Datefield,
Name = g.B.Name,
Surname = g.B.Surname,
PagaBruto = g.A.Sum(i => i.Bruto)
})).SelectMany(g => g);
Maybe this will work?
group a by new { a.personelID, b.Name, b.Surname, a.DateField} into grouping
select new
{
DateField = grouping.Key.DateField,
Name= grouping.Key.Name,
Surname= grouping.Key.Surname,
PagaBruto = grouping.Sum(i => i.Bruto)),
};

How to generate SQL COUNT(*) OVER (PARTITION BY {ColumnName}) in LINQ-to-SQL?

Is it possible to generate the following SQL query by using LINQ-to-SQL query expression or method chains which is defer-executable?
Data Structure
alt text http://www.freeimagehosting.net/uploads/e062a48837.jpg
Select Distinct ClassRoomTitle,
Count(*) Over(Partition By ClassRoomNo) As [No Sessions Per Room],
TeacherName,
Count(*) Over(Partition By ClassRoomNo, TeacherName) As [No Sessions Per Teacher] From ClassRoom
Expected Result
alt text http://www.freeimagehosting.net/uploads/47a79fea8b.jpg
Try this:
var vGroup = from p in ClassRoom
group p by new { p.ClassRoomNo, p.TeacherName }
into g
from i in g
select new
{
i.ClassRoomNo,
i.TeacherName,
i.ClassRoomTitle,
NoSessionsPerTeacher = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ClassRoomNo }
into g
from i in g
select new
{
i.ClassRoomTitle,
NoSessionsPerRoom = g.Count(),
i.TeacherName,
i.NoSessionsPerTeacher
};
var result = pGroup.OrderBy(p => p.ClassRoomNo).ThenBy(p => p.TeacherName);
I didn't test the above but you can check my original code in case I got something wrong in the rewrite:
var vGroup = from p in Products
group p by new { p.ProductId, p.VariantId }
into g
from i in g
select new
{
i.ProductId,
i.VariantId,
VariantCount = g.Count()
};
var pGroup = from p in vGroup
group p by new { p.ProductId }
into g
from i in g
select new
{
i.ProductId,
ProductCount = g.Count(),
i.VariantId,
i.VariantCount
};
var result = pGroup.OrderBy(p => p.ProductId).ThenBy(p => p.VariantId);
var classRooms = from c in context.ClassRooms
group c by new {c.ClassRoomNo} into room
select new {
Title = room.First().ClassRoomTitle,
NoSessions = room.Count(),
Teachers = from cr in room
group cr by new {cr.TeacherName} into t
select new {
Teacher = t.Key,
NoSessions = t.Count()
}
};
A bit more structured than the posted expected result, but I find that to be better.
You can always use SelectMany if you want to go back to unstructured:
var unstructured = classRooms
.SelectMany(c=> c.Teachers.Select( t=> new {
Title = c.Title,
SessionsPerRoom = c.NoSessions,
Teacher = t.Teacher,
SessionsPerTeacher = t.NoSessions
});

Categories

Resources