I have a DataTable with 8 fields. I want to return another DataTable that groups the first 7 fields and has the max value of the 8th. All fields are strings, the 8th is a number stored in a string field, e.g. "24".
Code that I've tried so far:
public DataTable highestVersion(DataTable dt)
{
DataTable dtResult=dt.Clone();
var query=from dtRow in dt.AsEnumerable()
group dtRow by new
{
b_r = dtRow["r"],
b_1 = dtRow["b_1"],
b_2 = dtRow["b_2"],
p_r = dtRow["p_r"],
p_1 = dtRow["p_1"],
p_2 = dtRow["p_2"],
p_f = dtRow["p_f"]
}
into maxVersion
select maxVersion.OrderByDescending(a => a["p_v"]).First();
foreach (var result in query)
{
dtResult.ImportRow(result);
}
return dtResult;
}
My expectation is that the group dtRow by new{}
should group by the first 7 and get only the highest element p_v
of each grouping by calling OrderByDescending().First()
. But this doesn't seem to actually do anything; all of the input rows are being returned.
EDIT: I just realized what the problem is. The values in p_f
are different from one another, e.g.
datarow 1
--------
r: "abc"
b_1: "def"
b_2: "ghi"
p_r: "jkl"
p_1: "mno"
p_2: "pqr"
p_f: "stu_this"
p_v: "18"
datarow 2
--------
r: "abc"
b_1: "def"
b_2: "ghi"
p_r: "jkl"
p_1: "mno"
p_2: "pqr"
p_f: "stu_that"
p_v: "24"
In this case I would want to only return DataRow 2, because 24>18, and be able to retrieve the stu_that
value.