我有一个结构如下的数据表:
username | price
"jack" .01
"jack" .02
"mary" .03
"mary" .04
我如何在 DataTable 上使用 LINQ 返回 MAX PRICE FOR JACK(例如:.02)?
设置表格的代码(可以忽略)。
DataTable tbl = new DataTable();
tbl.Columns.Add("username");
tbl.Columns["username"].DataType = typeof(string);
tbl.Columns.Add("price");
tbl.Columns["price"].DataType = typeof(double);
DataRow r = tbl.NewRow();
r["username"] = "jack"; r["price"] = .01;
tbl.Rows.Add(r);
r = tbl.NewRow();
r["username"] = "jack"; r["price"] = .02;
tbl.Rows.Add(r);
r = tbl.NewRow();
r["username"] = "mary"; r["price"] = .03;
tbl.Rows.Add(r);
r = tbl.NewRow();
r["username"] = "mary"; r["price"] = .04;
tbl.Rows.Add(r);
这是我卡住的地方。想要为 Jack 返回最高价格的一行(例如:“.02”)。
var result =
from row in tbl.AsEnumerable()
where (string) row["username"] == "jack"
group row by new {usernameKey = row["username"]} into g
select new
{
//WHAT IS THE LINQ SYNTAX TO USE HERE?
jackHighestPrice = g.Max(x => x.price); //This doesn't work, VS doesn't see the "price" field as strongly typed (not sure why).
};
//This should display Jack's highest price.
MessageBox.Show(result.First().jackHighestPrice.ToString());
我不确定如何让 Visual Studio 将“价格”字段识别为强类型。猜测与问题有关。
当然,两个查询都可以工作(一个按用户名过滤,另一个选择 Max,但不那么优雅。
与this answer相关.尝试了几乎所有的东西/四处寻找,但没有运气。
谢谢。
最佳答案
您不能以这种方式访问“价格”,因为 DataRow
上没有 price
成员。就像使用 username
一样访问它(按列名):
var result =
from row in tbl.AsEnumerable()
where (string) row["username"] == "jack"
group row by new {usernameKey = row["username"]} into g
select new
{
jackHighestPrice = g.Max(x => x["price"])
};
当然你可以简单地做:
string max = tbl.AsEnumerable()
.Where(row => row["username"].ToString() == "jack")
.Max(row => row["price"])
.ToString();
关于c# - DataTable:使用 LINQ 和条件字段 (GroupBy) 获取最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9550836/