How to get a minimum of multiple date columns in linq?

I have 3 date type columns in a table, and I want to get only one minimum date from all columns using linq.

Table: Collected in the processing stage 1/20/2017 02/19/2012 17.07.2012
4/21/2017 6/18/2014 12/15/2015

The required result: 6/18/2014

I am currently using the following code:

var collectedDate = queryResults.Min(d => d.Collected);
var stagedDate = queryResults.Min(d => d.Staged);
var ProcessedDate = queryResults.Min(d => d.Processed);

Then compare all these three and save the minimum date in another variable. How can I do this in another good way?

+4
source share
2 answers

You need to create Listwith collectedDate,stagedDate,ProcessedDateand then apply to it Linq. Please check it.

the 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;
    }
}

DotNetFiddle.

+2

:

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();
+1

Source: https://habr.com/ru/post/1676109/


All Articles