从Datatable中查找值与其max()值 - LINQ查询进行比较

时间:2011-09-29 09:07:10

标签: c#

感谢您的帮助。 实际上我有一个数据表发票,包含invoice_no,Invoice_dt,material_name,unit_price等字段。

但我需要找到项目的unit_price,这是该材料的最后日期条目{max(invoice_dt)}是否可能?

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

从上面我的意图是获取unit_price的最新日期条目,这将是当前的市场价格......

2 个答案:

答案 0 :(得分:1)

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;

如果要检索最大日期项目的价格,并且发票按材料名称分组:

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);
}

答案 1 :(得分:0)

实现这一目标的最简单方法是我可以使用扩展方法:

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);