C# 数据表:使用带有条件字段的 LINQ 获取最大值 (GroupBy)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9550836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 07:51:26  来源:igfitidea点击:

DataTable: Get Max Value Using LINQ With Criteria Field (GroupBy)

c#linqdatatable

提问by rr789

I have a DataTable structured like this:

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

username | price

"Hyman"        .01

"Hyman"        .02

"mary"       .03

"mary"       .04

用户名 | 价钱

“Hyman” .01

“Hyman” .02

“玛丽” .03

“玛丽” .04

How can I use LINQ on the DataTable to return the MAX PRICE FOR Hyman (ex: .02)?

如何在 DataTable 上使用 LINQ 来返回 MAX PRICE FOR Hyman(例如:.02)?

Code to setup the table (can ignore).

设置表格的代码(可以忽略)。

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"] = "Hyman"; r["price"] = .01;
tbl.Rows.Add(r);

r = tbl.NewRow();
r["username"] = "Hyman"; 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);

This is where I get stuck. Want to return one row for Hyman with his highest price (ex: ".02").

这就是我卡住的地方。想要以最高价格为 Hyman 返回一行(例如:“.02”)。

var result =
    from row in tbl.AsEnumerable() 
    where (string) row["username"] == "Hyman"
    group row by new {usernameKey = row["username"]} into g  
    select new
    {
        //WHAT IS THE LINQ SYNTAX TO USE HERE?    
        HymanHighestPrice = 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 Hyman's highest price.  
MessageBox.Show(result.First().HymanHighestPrice.ToString());

I'm not sure how to get Visual Studio to recognize the "Price" field as strongly typed. Guessing it's related to the issue.

我不确定如何让 Visual Studio 将“价格”字段识别为强类型。估计跟问题有关。

Of course, two queries will work (one to filter by username, then another to select Max but it's not as elegant.

当然,可以使用两个查询(一个按用户名过滤,然后另一个选择 Max,但它没有那么优雅。

Related to this answer. Tried just about everything/looked all over but no luck.

此答案相关。尝试了几乎所有的东西/看遍了但没​​有运气。

Thanks.

谢谢。

采纳答案by Andrew Whitaker

You can't access "price" that way since there's no pricemember on DataRow. Access it just like you're doing with username(by column name):

您无法以这种方式访问​​“价格”,因为 上没有price成员DataRow。像您一样访问它username(按列名):

var result =
    from row in tbl.AsEnumerable() 
    where (string) row["username"] == "Hyman"
    group row by new {usernameKey = row["username"]} into g  
    select new
    { 
        HymanHighestPrice = g.Max(x => x["price"])
    };

Of course you could simply do:

当然,您可以简单地执行以下操作:

string max = tbl.AsEnumerable()
        .Where(row => row["username"].ToString() == "Hyman")
        .Max(row => row["price"])
        .ToString();

回答by WorldIsRound

Did you try:

你试过了吗:

var query = tbl.AsEnumerable().Where(tr => (string) tr["username"] == "Hyman")
               .Max(tr => (double) tr["price"]);

回答by Olivier Jacot-Descombes

var result =
    from row in tbl.AsEnumerable()
    where (string)row["username"] == "Hyman"
    let x = new { usernameKey = (string)row["username"], (double)price = row["price"] }
    group x by x.usernameKey into g
    select g.Max(x => x.price);

However, since you allow only one user, grouping is not necessary. Just select the maximum as @WorldIsRound suggests.

但是,由于您只允许一个用户,因此不需要分组。只需按照@WorldIsRound 的建议选择最大值。