数据表:使用带有条件字段的LINQ获取最大值(GroupBy) [英] DataTable: Get Max Value Using LINQ With Criteria Field (GroupBy)

查看:330
本文介绍了数据表:使用带有条件字段的LINQ获取最大值(GroupBy)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a DataTable structured like this:

用户名|价格

username | price

"jack"       .01

"jack"        .01

"jack"       .02

"jack"        .02

玛丽"       .03

"mary"       .03

玛丽"       .04

"mary"       .04

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

How can I use LINQ on the DataTable to return the MAX PRICE FOR JACK (ex: .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"] = "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);

这就是我被困住的地方.想要以最高价格(例如:.02")为杰克退回一行.

This is where I get stuck. Want to return one row for Jack with his highest price (ex: ".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识别价格"字段为强类型.猜测与问题有关.

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

当然,两个查询将起作用(一个查询按用户名过滤,然后另一个查询选择Max,但这并不那么优雅.

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

此答案有关.尝试了几乎所有事物/看上去都没有,但是没有运气.

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

谢谢.

推荐答案

由于DataRow上没有price成员,因此无法访问价格".就像使用username一样访问它(按列名):

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

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();

这篇关于数据表:使用带有条件字段的LINQ获取最大值(GroupBy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆