c# - DataTable:使用 LINQ 和条件字段 (GroupBy) 获取最大值

标签 c# linq datatable

我有一个结构如下的数据表:

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/

相关文章:

.net - 需要帮助解决 LINQ 中 And 运算符的谓词错误

vb.net - 使用 VB 和 LINQ 对 <Object> 列表进行排序

c# - 如何在 UWP c# 中用 DataTable 内容填充 DataGrid

c# - 在 html 电子邮件中发送 DataTable 的内容,从 DataTable 生成 HTML 的首选方法是什么?

c# - WPF:TreeView 获取父节点

c# - IValueConverter.Convert 不会在 OneWay 绑定(bind)上被调用

c# - 如何使用 SWIG 将 IEnumerable 作为参数的 C++ 委托(delegate)从 C# 创建传递?

c# - 我怎样才能制作一个 pictureBox,当点击它时,它会在标签上显示一些文本?

c# - 使用 linq 2 实体检查 where 子句的两个条件

angular - 以 Angular 删除项目后无法刷新表