I have 3 date type column in a table and i want to get only one minimum date from all the columns using linq.
Table:
Collected Staged Processed
1/20/2017 2/19/2017 3/17/2016
4/21/2017 6/18/2014 12/15/2015
Needed result: 6/18/2014
Currently i am using following code:
var collectedDate = queryResults.Min(d => d.Collected);
var stagedDate = queryResults.Min(d => d.Staged);
var ProcessedDate = queryResults.Min(d => d.Processed);
And then comparing these all three and store the minimum date in another variable. How can i do it in some other good way?
As you working with database, it will be better to make one query instead of three:
var answer = (from item in queryResults
group item by 0 into sub
select new
{
min1 = sub.Min(x => x.Collected),
min2 = sub.Min(x => x.Staged),
min3 = sub.Min(x => x.Processed)
}).ToList().Select(x => new[] { x.min1, x.min2, x.min3 }.Min()).FirstOrDefault();
You have to create List
using collectedDate,stagedDate,ProcessedDate
then apply Linq
on it. Please check this.
Code:
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public class Test
{
public DateTime Collected {get; set;}
public DateTime Staged {get; set;}
public DateTime Processed {get; set;}
}
public static void Main()
{
List<Test> queryResults = new List<Test>();
queryResults.Add(new Test(){Collected=Convert.ToDateTime("1/20/2017"),Staged=Convert.ToDateTime("2/19/2017"),Processed=Convert.ToDateTime("3/17/2016")});
queryResults.Add(new Test(){Collected=Convert.ToDateTime("4/21/2017"),Staged=Convert.ToDateTime("6/18/2014"),Processed=Convert.ToDateTime("12/15/2015")});
var collectedDate = queryResults.Min(d => d.Collected);
var stagedDate = queryResults.Min(d => d.Staged);
var ProcessedDate = queryResults.Min(d => d.Processed);
List<DateTime> listDate = new List<DateTime>(){collectedDate,stagedDate,ProcessedDate};
Console.WriteLine(listDate.Min(d => d));
//2nd Solution
//Compare DateTime between column and then rows to get min value
Console.WriteLine(queryResults.Min(d => getMin(getMin(d.Collected, d.Staged), d.Processed)));
}
//Function to compare two DateTime
public static DateTime getMin(DateTime a, DateTime b)
{
return a < b ? a : b;
}
}
You can check output of the code in DotNetFiddle.
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