I have an SQL table with the following design:
TableSchedule:
Id
Description
ImportedDate
I can import a large number of items and they will all have the same ImportedDate.
How can I write a LINQ query that grabs only the entries with the most recent ImportedDate?
var ResultSchedule =
from a in Db.TableSchedule
where a.ImportedDate == (Newest?)
Try This
var ResultSchedule =
from a in Db.TableSchedule
where a.ImportedDate == (from item in DB.TableSchedule Select item.ImportedDate).Max()
Try this:
Select * From Table
Where ImportedDate =
(Select max(ImportedDate) From Table)
If you need the latest record for each [something] like, say, for each individual customer, then make the siubquery correlated
Select * From Table t
Where ImportedDate =
(Select max(ImportedDate)
From Table
Where Customer = t.Customer)
How about this:
var ResultSchedule = from a in Db.TableSchedule
let max = Db.TableSchedule.Max(i => i.ImportedDate)
where a.ImportedDate == max
select a;
You can group the results and order them by date:
var ResultsSchedule = Db.TableSchedule.
GroupBy(a => a.ImportedDate).
OrderByDescending(g => g.Key).
FirstOrDefault().
Select(g => g);
In fluent syntax:
var ResultSchedule =
Db.TableSchedule.Where(
a => a.ImportedDate.Equals(Db.TableSchedule.Max(b => b.ImportedDate))
);
Related
I have this type of code. In Material table it only have one MaterialId. But in Report table it can be multplie MaterialId rows.(One materialId can have multplie rows in Report table).
But in the Material table i do not have any Timestamp. But in Report there are a column as TimeStamp which I want to use to get the latest.
I only want distinct values with the ReportAdminModel as it is right now.
But how do I get it to work like that?
I have tried Distinct() but that does not work.
list = (from material in db.Material
join reports in db.Report on material.MaterialId equals reports.MaterialId
select new ReportAdminModel
{ MaterialId = material.MaterialId, MaterialStatus = material.ProcessApprovalStatus, FlowIndex = material.FlowIndex, ActualStartTime = reports.Timestamp })
.OrderByDescending(x => x.ActualStartTime).Take(item.NumberOfRows.Value).ToList();
If I understood correctly, try this :
list = (from material in db.Material
join reports in (from rep in db.Report
group rep by rep.MaterialId into grp
let latestTimeStamp = grp.Max(o => o.Timestamp)
select new
{
MaterialId = grp.Key,
Timestamp = latestTimeStamp,
//if you need any other field, just do something like :
//SomeField = grp.Where(o => o.Timestamp == latestTimeStamp).Select(o => o.SomeField).FirstOrDefault();
})
on material.MaterialId equals reports.MaterialId
select new ReportAdminModel
{MaterialId = material.MaterialId,
MaterialStatus = material.ProcessApprovalStatus,
FlowIndex = material.FlowIndex,
ActualStartTime = reports.Timestamp,
}).OrderByDescending(x => x.ActualStartTime).ToList();
You could apply group by material.MaterialId, material.ProcessApprovalStatus, material.FlowIndex and retrieve the last Timestamp data for per group item.
list = (from material in db.Material
join reports in db.Report on material.MaterialId equals reports.MaterialId
group new{material,reports} by new { material.MaterialId, material.ProcessApprovalStatus, material.FlowIndex } into materialGrouped
select new ReportAdminModel
{
MaterialId = materialGrouped.Key.MaterialId,
MaterialStatus = materialGrouped.Key.ProcessApprovalStatus,
FlowIndex = materialGrouped.Key.FlowIndex,
ActualStartTime = materialGrouped.Max(x => x.reports.TimeStamp)
})
.OrderByDescending(x => x.ActualStartTime).Take(item.NumberOfRows.Value).ToList();
I am trying to write SQL query in LINQ to SQL but after 4h of trying i gave up.
select B.* from Bid B
join
(
select BidId, max(BidVersion) as maxVersion
from Bid
group by BidId
) X on B.BidId = X.BidId and B.BidVersion = X.maxVersion
i saw some tips on the stackOverflow but they werent helpful.
I am using some VERY bad code like:
List<Bid> bidEntities = new List<Bid>();
var newest = from bid in _dbContext.Bids
group bid by bid.BidId into groups
select new { Id = groups.Key, Vs = groups.Max(b => b.BidVersion) };
foreach (var group in newest)
{
bidEntities.Add(await _dbContext.Bids.Where(b => b.BidId == group.Id && b.BidVersion == group.Vs).SingleOrDefaultAsync());
}
Thank you for any advice.
Something like this should work:
var rows = Bids
.GroupBy(b => b.BidId)
.Select(g => g.OrderByDescending(gg => gg.BidVersion).FirstOrDefault())
With LINQ, it helps sometimes not to think in the 'SQL way', but about what you really want. You want the highest version bid for each BidId
So the scenario is I have a table of items, and for each item there is a number of comments in another table. I want to get a list of the items with the LATEST comment.
I did this:
var res = (from i in db.Item
select new
{
ID = i.ID,
Name = i.Name,
Comment = (from c in db.Comment
orderby c.Created descending
where c.Item == i.ID
select new { Message = c.Message }).FirstOrDefault().Message
});
Ok, this gets me the results I want, but it's so SLOW... Please, help me make a join out of this instead!
Thank you!
Try this:
var res = db.Item.Join(db.Comment, x=>x.ID, x=>x.ID, (x,y)=>new{x,y})
.OrderByDescending(a=>a.y.Created)
.GroupBy(a=>a.x.ID,(key,items)=>items.First())
.Select(a=> new {
a.x.ID,
a.x.Name,
a.y.Message
});
First, I'm grabbing ClientID. Then, I get all Invoices associated with that ClientID. I want to return data all ordered by InvoiceNumber, descending. Here's my code:
var rvInvoices =
(from i in db.QB_INVOICES_HEADER
where i.ClientID == cId
select i).ToList();
foreach (var itm in rvInvoices)
{
InvoiceModel cm = new InvoiceModel()
{
InvoiceNumber = itm.InvoiceNumber,
InvoiceSentDt = itm.InvoiceSentDt,
InvoiceDt = itm.InvoiceDt,
Amount = itm.Amount,
Term = itm.Term,
ClientName = itm.CI_CLIENTLIST.ClientName
};
listInvoices.Add(cm);
}
return listInvoices;
listInvoices.OrderByDescending(x => x.InvoiceNumber).ToList()
You should try something like this:
var rvInvoices =
(from i in db.QB_INVOICES_HEADER
where i.ClientID == cId
select i).OrderByDescending(x => x.InvoiceNumber);
And I don't see a reason you need to call .ToList().
You can do the order in three places.
In the initial query,
In the foreach, or
In the return
Option 1:
var rvInvoices =
(from i in db.QB_INVOICES_HEADER
where i.ClientID == cId
select i).OrderByDescending(i => i.InvoiceNumber).ToList();
Option 2:
foreach (var itm in rvInvoices.OrderByDescending(i => i.InvoiceNumber))
Option 3:
return listInvoices.OrderByDescending(i => i.InvoiceNumber).ToList();
I would suggest taking route 1 since it will run the order at the database level.
You should order them on the database instead of the client:
var rvInvoices = db.QB_INVOICES_HEADER
.Where(i => i.ClientID == cId)
.OrderByDescending(i => i.InvoiceNumber);
The method you currently have creates multiple lists, has an explicit foreach loop, and needs to have its output sorted. It can be done with just creating a single list, no explicit looping, and with the database doing the sorting for you:
return
(from i in db.QB_INVOICES_HEADER
where i.ClientID == cId
// have the database do the sorting
orderby i.InvoiceNumber descending
select i)
// break out of the DB query to make InvoiceModel
.ToEnumerable()
.Select(itm => new InvoiceModel()
{
InvoiceNumber = itm.InvoiceNumber,
InvoiceSentDt = itm.InvoiceSentDt,
InvoiceDt = itm.InvoiceDt,
Amount = itm.Amount,
Term = itm.Term,
ClientName = itm.CI_CLIENTLIST.ClientName
})
// only create one list as the last step
.ToList();
I'm at the finish line for my university project, and I'm kinda stuck at finishing a query.
The working query looks like this:
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
};
I would really appreciate it if you can show me, how to Order the results by the given "Quantity" in descending order.
Thanks!
var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
})
.OrderByDescending(order => order.Quantity);
Please do this :
var Report = (from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
select new Orders
{
Seller = qGroup.Key,
Quantity = qGroup.Sum(p => int.Parse(p.Element("quantity").Value)).ToString()
}).OrderByDescending(x => x.Quantity);
HTH !!!!
(Kudos to LINQ Orderby Descending Query )
The answers by Skippy and Andrei work, but you can also write as
var Report = from query in Document.Descendants("order")
group query by query.Element("seller").Value
into qGroup
let qty = qGroup.Sum(p =>int.Parse(p.Element("quantity").Value)).ToString()
orderby qty descending
select new Orders
{
Seller = qGroup.Key,
Quantity = qty
};
if you'd rather keep it all in one syntax.