我有一个像这样结构的DataTable:
用户名| 价钱
"杰克".01
"杰克".02
"玛丽".03
"玛丽".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);
这是我被卡住的地方.想以最高价格为杰克退回一行(例如:".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,但它不那么优雅.
与此答案相关.几乎尝试了一切/看了一遍但没有运气.
谢谢.
And*_*ker 10
由于没有price会员,您无法以这种方式访问"价格" DataRow.像访问它一样访问它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();
你试过了吗:
var query = tbl.AsEnumerable().Where(tr => (string) tr["username"] == "jack")
               .Max(tr => (double) tr["price"]);
| 归档时间: | 
 | 
| 查看次数: | 35721 次 | 
| 最近记录: |