Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Maximum Date value from X tables in DataSet

Tags:

c#

linq

datatable

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.

like image 647
Dor Lugasi-Gal Avatar asked Dec 27 '18 09:12

Dor Lugasi-Gal


1 Answers

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();
  • Uses Enumerable.Range to generate the indices enabling us to access each individual DataTable.
  • Uses SelectMany to get a single IEnumerable<DataRow>
  • Uses 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();
  • Uses Enumerable.Range to generate the indices enabling us to access each individual DataTable.
  • Uses Select to get an IEnumerable<DateTime> consisting of the maximum DateTime of each DataTable
  • Uses Max to get the maximum value of the of the DateTime's and then convert to a string representation.
like image 68
Ousmane D. Avatar answered Oct 11 '22 11:10

Ousmane D.