C# Sorting DateTime issue - c#

I am setting up a list of date times:
DateTime a1
DateTime a2
DateTime a3
DateTime a4
The above looks like this (as DateTime objects):
3/1/2012 10:56
3/1/2012 17:03
3/1/2012 1:38
3/1/2012 5:33
Then I put them in a list and sort:
List<DateTime> ldtBites = new List<DateTime>();
ldtBites.Add(a1);
ldtBites.Add(a2);
ldtBites.Add(a3);
ldtBites.Add(a4);
ldtBites.Sort();
After Sorting I get this:
3/1/2012 1:38:00 AM
3/1/2012 10:56 AM
3/1/2012 5:03:00 PM
3/1/2012 5:33:00 AM

You omitted the definition of w,x,y,z. I defined them as such:
DateTime w = new DateTime(2012, 3, 1, 10, 56, 0);
DateTime x = new DateTime(2012, 3, 1, 17, 3, 0);
DateTime y = new DateTime(2012, 3, 1, 1, 38, 0);
DateTime z = new DateTime(2012, 2, 29, 17, 3, 0);
This causes them to match your values for a1-a4; however, when I run the rest of your code, they sort correctly (a3, a4, a1, a2).
However, I noticed that x and z were the same hour/minute, so my initial test had this:
DateTime z = new DateTime(2012, 3, 1, 17, 3, 0);
When I ran this, I got them to come out in the order you were showing (a3, a1, a2, a4); however, after the AddHours() call went through, the z value was actually 3/2/2012, which is why it was last.

You don't want to convert back and forth. Just do it once. Sort your list first, and only then convert to string.

Converting to string and converting back might cause that result. Why don't you add x,y,w,z to your list directly?
List<DateTime> ldtBites = new List<DateTime>();
ldtBites.Add(DateTime.Parse("3/1/2012 10:56"));
ldtBites.Add(DateTime.Parse("3/1/2012 17:03"));
ldtBites.Add(DateTime.Parse("3/1/2012 1:38"));
ldtBites.Add(DateTime.Parse("3/1/2012 5:33"));
ldtBites.Sort();
foreach (DateTime dt in ldtBites)
Console.WriteLine(dt);
Output:
3/1/2012 1:38:00 AM
3/1/2012 5:33:00 AM
3/1/2012 10:56:00 AM
3/1/2012 5:03:00 PM
Press any key to continue . . .

Above will work only if all the date are same, in case the date are also different you should do the following...
var sortedDates = dates.OrderByDescending(x => x);
or else Don't want to use, or don't know Linq then you can go for following..
static List SortAscending(List list)
{
list.Sort((a, b) => a.CompareTo(b));
return list;
}
static List SortDescending(List list)
{
list.Sort((a, b) => b.CompareTo(a));
return list;
}

Related

how to get a date from a datetime offset in linq

I have a table that has date time stored as follows
2022-02-01 17:47:50.3483971 +00:00
2022-05-11 18:47:50.3483971 +00:00
2022-05-21 14:40:50.3483971 +00:00
I'm trying to write a linq query that will compare get results for the date passed but i only want to pass in the date, for example get the records from 2022/02/01
so I tried
var fdate= query.filteredDate.LocalDateTime.ToShortDateString(); // this gets the date the user passes in.
the problem comes in the where clause when I try this
filteredResult.Where(x=> fdate >= DateTime.Parse(x.storeddate.LocalDateTime.ToShortDateString()))
then it errors out and says can not be applied to string and datetime
so I tried this
Where(x=> fdate >= x.storeddate.LocalDateTime.ToShortDateString()))
and it says can not be applied to string and string
what am I doing wrong?
here I've write an some code to resolve your issue:
List<DateTime> ListDatesToCompare = new List<DateTime>(); //that list simulate your input list
ListDatesToCompare.Add(new DateTime(2022, 02, 01, 17, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 11, 18, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 21, 14, 40, 50, 348, DateTimeKind.Utc));
//this is your filter in string format
string fdate = "2022/02/01";
//for this example i've forced the culture info to be sure that the date will be correctly parsed (here some documentation: https://stackoverflow.com/questions/13797727/datetime-and-cultureinfo)
DateTime fDateParsed = DateTime.Parse(fdate, new System.Globalization.CultureInfo("en-EN"));
//here the result query
List<DateTime> ResultOfQuery = ListDatesToCompare.Where((DateTime CurrentDT) =>
{
//you can do this comparison because the variables has the same type.
return CurrentDT >= fDateParsed;
}).ToList();
I hope the code and my english is understandable,
if you need something else text to me.

Get closest day in future in a LINQ expression

I have date list in yyyy/mm/dd:
2020/06/10
2020/06/18
2020/07/17
and given date
2020/06/10
I want to find closest day in future from the given date in LINQ (expected result: 2020/06/18).
If you mean to find the closest date in future then you can filter out all earlier dates (including the same date), order it and then take the first value:
List<DateTime> allDates = new List<System.DateTime>()
{
new DateTime(2020, 06, 10),
new DateTime(2020, 06, 18),
new DateTime(2020, 07, 17),
};
DateTime givenDate = new DateTime(2020, 06, 10);
DateTime closestDateInFuture = allDates.Where(x => x > givenDate).OrderBy(x=> x).First();
Console.WriteLine(closestDateInFuture);
Output:
18.06.2020 00:00:00
Another suggestion by #Johnathan Barclay is to use the Min method, which yields the same result:
DateTime closestDateInFuture = allDates.Where(x => x > givenDate).Min()

how to remove date from datetime in Linq c#

i want to get only time from a datetime variable in linq query.
for eaxample if i have an array of datetime having values
["02/12/1970 14:52:06","14/06/2015 12:32:44"]
then how to extract minimum time from it so that i get output like
"12:32:44"
as if i take minimum these two it will give output
"14:52:44" instead of "12:32:44"
as the datepart of first value is smaller than the other.
i try this code:
time1 = table1.Min(x=>x.StartTime)
but it will give "14:52:06" as output
any suggestions?
First extract Time from DateTime and then get Min value
var dates = new List<DateTime>
{
new DateTime(2020, 6, 9, 12, 35, 45),
new DateTime(2020, 6, 10, 11, 35, 45)
};
var minTime = dates
.Select(d => d.TimeOfDay)
.Min();
#Update
If you want to get DateTime object that has the smallest time part, then use this:
var dateWithMinTime = dates
.OrderBy(d => d.TimeOfDay)
.FirstOrDefault();
Try
table1.Min(c => c.StartTime.TimeOfDay)
assuming StarTime is a DateTime.

DateTimeOffset proper usage

If I have a DateTime instance which represents a valid UTC time, and an offset that converts that DateTime to the time zone where it applies, how do I construct a DateTimeOffset instance to represent this?
var utcDateTime = new DateTime(2011, 02, 29, 12, 43, 0, /*DateTimeKind.Utc*/);
var localOffset = TimeSpan.FromHours(2.0);
var dto = ...
// Here the properties should be as follows;
// dto.UtcDateTime = 2011-02-29 12:43:00
// dto.LocalDateTime = 2011-02-29 14:43:00
Perhaps I'm not understanding the DateTimeOffset structure correctly, but I'm unable to get the expected output.
Thanks in advance
Looks like you want:
var utcDateTime = new DateTime(2012, 02, 29, 12, 43, 0, DateTimeKind.Utc);
var dto = new DateTimeOffset(utcDateTime).ToOffset(TimeSpan.FromHours(2));
Note that I changed the year from 2011 (which is not a leap year and does not have 29 days in February) to 2012.
Test:
Console.WriteLine("Utc = {0}, Original = {1}", dto.UtcDateTime, dto.DateTime);
Output:
Utc = 2/29/2012 12:43:00 PM, Original = 2/29/2012 2:43:00 PM
Do note that you probably don't want the LocalDateTime property, which may represent the instant in time as of the local system's timezone.

Linq group month by quarters

Is it possible to do a linq group by and group months into quarters, Ie Q1 Jan to apr etc etc
Something like this
Enumerable.Range(1,12)
.Select(o => new DateTime(DateTime.Today.Year, o, 1))
.GroupBy(o => (o.Month - 1) / 3)
Here's a basic example demonstrating this:
var dates = new[]
{
new DateTime(2011, 12, 25),
new DateTime(2011, 11, 25),
new DateTime(2011, 5, 4),
new DateTime(2011, 1, 3),
new DateTime(2011, 8, 9),
new DateTime(2011, 2, 14),
new DateTime(2011, 7, 4),
new DateTime(2011, 11, 11)
};
var groupedByQuarter = from date in dates
group date by (date.Month - 1)/3
into groupedDates
orderby groupedDates.Key
select groupedDates;
foreach(var quarter in groupedByQuarter)
{
Console.WriteLine("Q: {0}, Dates: {1}", quarter.Key, string.Join(", ", quarter));
}
The order by is there to simply help the quarters be logically ordered. You can remove the whole clause following the group statement.
With the output of:
Q: 0, Dates: 1/3/2011 12:00:00 AM, 2/14/2011 12:00:00 AM
Q: 1, Dates: 5/4/2011 12:00:00 AM
Q: 2, Dates: 8/9/2011 12:00:00 AM, 7/4/2011 12:00:00 AM
Q: 3, Dates: 12/25/2011 12:00:00 AM, 11/25/2011 12:00:00 AM, 11/11/2011 12:00:00 AM
Obviously you will need to correct the quarter numbers by adding one or perhaps translating them to a corresponding enum.
you can divide an arbitrary list into parts using an overload of the Select method and GroupBy. In your case, assuming the months in the list are in the correct order, the following should work:
var groups = yourList
.Select((item, index) => new { item, index })
.GroupBy(indexedItem=>indexedItem.index/3);
Yes it can be achieved with the LINQ to SQL GroupBy function if you define the qouters somewhere in your database or you can write some code that will handle this action it all depends on what data is available to you for this evaluation.

Categories

Resources