I am using the following query which I believe should filter my results to return only unique DateTimes but as you can see it is not working; records 2 and 3 are identical in the following image. Each of those records is a clone of another so the dates should be identical in case milliseconds or something I cannot see is affecting the result. Appreciate any insight.
Asked
Active
Viewed 114 times
-2
-
4Please, check if dates of interest have *fractions of seconds*: `12/1/4:22:32.001 != 12/1/4:22:32.005` – Dmitry Bychenko Dec 16 '21 at 22:43
-
2Are you sure the milliseconds are identical? – maraaaaaaaa Dec 16 '21 at 22:43
-
2(The debugger doesn't show milliseconds in its tooltips) – Caius Jard Dec 16 '21 at 22:47
-
The base value of a `DateTime` is the `Tick` or 1/10,000 of millisecond. It is unlikely they are all the same even if the month or even second are the same – Ňɏssa Pøngjǣrdenlarp Dec 16 '21 at 22:53
-
1Incidentally, it might not matter if this is being translated to SQL but it might be quicker to do your OrderBy after your Distinct in other contexts.. no point sorting a million items, then throwing 999,998 away; should throw away first then sort the reduced remainder – Caius Jard Dec 16 '21 at 22:54
2 Answers
0
It seems that dates have different fractions of seconds. That's why you see
12/5/2021 8:30:48 PM
12/5/2021 8:30:48 PM
when actual dates are something like these
12/5/2021 8:30:48.123 PM
12/5/2021 8:30:48.234 PM
Let's either drop these milliseconds:
...
.Select(x => new DateTime(x.Year, x.Month, x.Day, x.Hour, x.Minute, x.Second))
.Distinct()
...
Or round them to nearest second
...
.Select(x => new DateTime(x.Year, x.Month, x.Day, x.Hour, x.Minute, x.Second)
.AddSeconds(x.Millisecond / 500))
.Distinct()
...

Dmitry Bychenko
- 180,369
- 20
- 160
- 215
0
Distinct
compares against exact duplicates. Your screenshot doesn't show milliseconds. So you're almost guaranteed that the values are not the same, even though the minutes may be.

Jonathan Wood
- 65,341
- 71
- 269
- 466
-
Thank you!!! I used the solution here to round the milliseconds for comparing and that solved the issue: https://stackoverflow.com/questions/1004698/how-to-truncate-milliseconds-off-of-a-net-datetime – Julian Dormon Dec 16 '21 at 23:30