Sunday, October 26, 2014

get max and min of date from comma text file

This is the answer using LINQ:



// LINQ elegant code
using (StreamReader sr = new StreamReader(ofd.FileName))
{
string line;
var lines = new List<string[]>(); // Create a list to put the lines.
while ((line = sr.ReadLine()) != null)
lines.Add(line.Split(',')); // process each line and put on the list
var dates = (from l in lines
select new { Date = DateTime.ParseExact(l[1],"yyyyMMdd",null)}); // Get the day of each value, this can be used to get all the fields.
var min = dates.Min(d=> d.Date); // Ask the Min Date
var max = dates.Max(d=>d.Date); // Ask the Max Date

Console.WriteLine(min.ToString());
Console.WriteLine(max.ToString());
}
//LINQ Short code with no date time conversion
using (StreamReader sr = new StreamReader(ofd.FileName))
{
string line;
var lines = new List<string[]>(); // Create a list to put the lines.
while ((line = sr.ReadLine()) != null)
lines.Add(line.Split(',')); // process each line and put on the list

var min = lines.Min(l=> l[1]); // Ask the Min Date
var max = lines.Max(l=> l[1]); // Ask the Max Date

Console.WriteLine(min.ToString());
Console.WriteLine(max.ToString());
}



and the output is:


6/23/2012 12:00:00 AM

6/25/2012 12:00:00 AM

20120623

20120625




Don't forget to mark the best replies as answers!



No comments:

Post a Comment