2011-09-29 88 views
0

感謝您的幫助。 其實我有一個DataTable發票,具有類似於invoice_no,Invoice_dt,material_name,UNIT_PRICE等領域..從Datatable中查找與其max()值比較的值 - LINQ查詢

但我需要找到這對於材料{最大值(invoice_dt)的最後日期進入該項目的UNIT_PRICE } 可能嗎?

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

從上面我的意圖是讓UNIT_PRICE的最新日期的條目,這將是目前的市場價格...

回答

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

真的,我嘗試從單一的LINQ查詢 – Paramu

+0

@Paramu學習然後你就可以通過invoice.Max(T1 => t1.invoice_dt)在第二條語句 –

+0

取代的maxDate @vc 74:做你建議什麼: (invoice_dt = new DateTime(2010,11,11),material_name =「Wood」,unit_price = 10} {invoice_dt = new DateTime(2010,12,12) invoice_dt = new DateTime(2011,1,1),material_name =「Iron」,unit_price = 12} 和'MyMaterial'設置爲'Wood'給我一個空的結果集。 – Jeroen

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