[英]Select from DataTable most recent result for each item
我有一個包含數千行的數據表。 表格中有序列號列和測試編號列。 如果測試了一個以上的序列,則測試編號會遞增。 我需要能夠從我的數據表中為每個序列選擇最新的測試,然后將其插入另一個數據表中。 目前,我正在使用此:
DataTable newdata = data.AsEnumerable().Where(x => x.Field<Int16>("Test") ==
data.AsEnumerable().Where(y => y.Field<string>("Serial") ==
x.Field<string>("SerialNumber")).Select(y =>
y.Field<Int16>("Test")).Max()).Select(x => x).CopyToDataTable();
這樣做確實可以完成工作,但是很顯然它的效率非常低。 是否有更有效的方法為每個序列號選擇數據的第一行?
謝謝
解
因此,根據Cam Bruce的回答,我用Dictionary而不是join實現了以下代碼:
//Get all of the serial numbers and there max test numbers
Dictionary<string, Int16> dict = data.AsEnumerable().GroupBy(x => x.Field<string>("SerialNumber")).ToDictionary(x => x.Key, x => x.Max(y => y.Field<Int16>("Test")));
//Create a datatable with only the max rows
DataTable newdata = data.AsEnumerable().Where(x => x.Field<Int16>("Test") ==
dict[x.Field<string>("SerialNumber")]).Select(x => x).CopyToDataTable();
//Clear the dictionary
dict.Clear();
這將為您提供每個序列號和Max
測試。 然后,您可以將該結果集重新連接到DataTable
以獲取所有最大行。
var maxTest= data.AsEnumerable()
.GroupBy(g=> g.Field<string>("SerialNumber"))
.Select(d=> new
{
SerialNumber = g.Key
Test = g.Max(g.Field<Int16>("Field"))
};
var maxRows = from d in data.AsEnumerable()
join m in maxTest
on new { S = d.Field<string>("SerialNumber"), T = d.Field<Int16>("Test") }
equals new { S = m.SerialNumber, T = m.Test }
select d;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.