Madhu Gowda
Madhu Gowda

Reputation: 3

Is there way to get the max value from YYYYMM combination?

Eg: I have 2020M01 ,2019M12,2020M03 in datarow[]. How can i fetch max value i.e 2020M03

Upvotes: 0

Views: 134

Answers (3)

Caius Jard
Caius Jard

Reputation: 74605

You say you have an array of DataRow, so I assume your dates must be in some column of the row

I'd thus say you need something like:

myDataRowArray.Max(ro => ro["nameOfYourDateColumn"].ToString());

If you mean that all your dates are in different columns of the same datarow, it's a bit more tricky. If there is nothing else in the row other than these dates, then it can be done with the row's ItemArray, an array of object representing each value of row's cells:

myDataRow.ItemArray.Max(elem => elem.ToString());

If there are some columns of the datarow that are your dates and some that are not, you're going to need to pull them out. Here I extract 3 different columns and put their values to a string array, then find the max:

new[] { 
  myRow["date1Column"].ToString(), 
  myRow["date2Column"].ToString(), 
  myRow["date3Column"].ToString() 
}.Max();

Upvotes: 0

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131324

This isn't an unusual format. Such formats ensure that date literals can be sorted alphabetically. YYYY-MM-DD and YYYYMMDD can be sorted alphabetically too.

This means that you can find the minimum or maximum value in a list simply by using the Min() or Max() LINQ functions, eg :

var months=new[]{ "2020M01" ,"2019M12","2020M03"};
var latestMonth=months.Max();
var earliestMonth=months.Min();

Upvotes: 1

Neil
Neil

Reputation: 11889

Your date format looks like it can be string sorted:

var dates = new System.Collections.Generic.List<string> { "2020M01", "2019M02", "2020M03" };
var max = dates.OrderByDescending(x => x).FirstOrDefault();

Or, as @panagiotis points out, Max() would also work:

var max = dates.Max();

Upvotes: 2

Related Questions