Note that there are some explanatory texts on larger screens.

plurals
  1. PODataTable: Get Max Value Using LINQ With Criteria Field (GroupBy)
    text
    copied!<p>I have a DataTable structured like this: </p> <blockquote> <p>username | price </p> <p>"jack"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.01</p> <p>"jack"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.02</p> <p>"mary"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.03</p> <p>"mary"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.04</p> </blockquote> <p>How can I use LINQ on the DataTable to return the MAX PRICE FOR JACK (ex: .02)? </p> <p>Code to setup the table (can ignore). </p> <pre><code>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); </code></pre> <p>This is where I get stuck. Want to return one row for Jack with his highest price (ex: ".02"). </p> <pre><code>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 =&gt; 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()); </code></pre> <p>I'm not sure how to get Visual Studio to recognize the "Price" field as strongly typed. Guessing it's related to the issue. </p> <p>Of course, two queries will work (one to filter by username, then another to select Max but it's not as elegant. </p> <p>Related to <a href="https://stackoverflow.com/a/3299573/722945">this answer</a>. Tried just about everything/looked all over but no luck. </p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload