简体   繁体   中英

Find a value from Datatable compare with its max() value - LINQ Query

thanks for helps. Actually I have a datatable Invoice, having fields like invoice_no, Invoice_dt, material_name, unit_price, etc..

But I need to find the unit_price of the item which is the last date entry for that material {max(invoice_dt)} is it possible?

var query = from t1 in invoice
        where t1.material_name == MyMaterial && t1.invoice_dt == (invoice.max(invoice_dt))
        select t1.unit_price;

From the above my intention is to get the latest date entry of unit_price, that will be the current market price...

var maxDate = invoice.Max(t1 => t1.invoice_dt);
var query = from t1 in invoice
        where t1.material_name == MyMaterial && t1.invoice_dt == maxDate)
        select t1.unit_price;

If you want to retrieve the price for the max date item with the invoices grouped by material name:

var groupedInvoices = invoice.GroupBy(t1 => t1.material_name);
foreach (var group in groupedInvoices)
{
    var maxDate = group.Max(t1 => t1.invoice_dt);
    var maxDateItem = group.Single(item => item.invoice_dt == maxDate);
    Console.WriteLine(maxDateItem.unit_price);
}

The easiest way to accomplish this I could come up with was using extensions methods:

var query = invoice.SingleOrDefault(item => item.invoice_dt ==
    invoice.Where(inv => inv.material_name == MyMaterial).
    Max(inv => inv.invoice_dt)).Select(i => i.unit_price);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM