I have a DataSet with 1-3 tables, each table have a column named m_date (string) I want to get max value from all of them using LINQ.
I know how to get each table Maximum value:
var maxDate=ds.Tables[index].AsEnumerable()
.Max(x=>DateTime.Parse(x["m_date"].ToString())).ToString();
but I don't know how to get Max value from all the tables information
Edit:
I now have something like this which works:
DateTime maxDate=DateTime.MinValue;
foreach (DataTable tbl in ds.Tables)
{
DateTime maxDateCur=ds.Tables[index].AsEnumerable()
.Max(x=>DateTime.Parse(x["m_date"].ToString()));
maxDate=new DateTime[] {maxDateCur,maxDate}.Max();
}
but I have a feeling it could be done better.
You could do it as:
var maxDate = Enumerable.Range(0, ds.Tables.Count)
.SelectMany(index => ds.Tables[index].AsEnumerable())
.Max(dataRow => dataRow.Field<DateTime>("m_date"))
.ToString();
Enumerable.Range
to generate the indices enabling us to access each individual DataTable
.SelectMany
to get a single IEnumerable<DataRow>
Max
to get the maximum value and convert it to a string.Slightly different variant would be:
var maxDate = Enumerable.Range(0, ds.Tables.Count)
.Select(index =>
ds.Tables[index].AsEnumerable()
.Max(dataRow => dataRow.Field<DateTime>("m_date")))
.Max().ToString();
Enumerable.Range
to generate the indices enabling us to access each individual DataTable
.Select
to get an IEnumerable<DateTime>
consisting of the maximum DateTime
of each DataTable
Max
to get the maximum value of the of the DateTime's and then convert to a string representation.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With