John
John

Reputation: 1051

Find the min/max value in a column of a DataTable with Where clause?

Say for example I have this DataTable:

enter image description here

Is it possible to get the min/max value of Day1 column based on the Year column? Possibly using a select statement?

In SQL you would do: SELECT MIN(Day1), Max(Day1) FROM TST WHERE Year = 2015

Upvotes: 1

Views: 2959

Answers (1)

ChrisF
ChrisF

Reputation: 137148

I'm not sure whether you can do it in one statement, but you can do it in two using LINQ:

var minValue = tst.Where(t => t.Year == 2015).Min(t => t.Day1);
var maxValue = tst.Where(t => t.Year == 2015).Max(t => t.Day1);

tst needs to be something that LINQ recognises like a List, IEnumerable or Array.

You can use the Select method to get an array from the DataTable, and even do the first filter:

var data = tst.Select("Year = 2015", "Day1 ASC").ToList(); // Not that you need it sorted
var minValue = data.Min(t => t.Day1);
var maxValue = data.Max(t => t.Day1);

Upvotes: 4

Related Questions