So I'm doing a database query using LINQ with this (sanitized) code:
var dateList =
Table1.Where(t1 => t1.column1.Contains(stringUsed)) //stringUsed is a parameter of the method containing this code
.Join(Table2, t1 => t1.columnName2, t2 => t2.columnName2,
(t1, t2) => new {t1, t2})
.Join(Table3, t1t2 => t1t2.t1.column3, t3 => t3.column3,
(t1t2, t3) => new {Date = t3.column4})
.Select(d => d.Date.Value) //Dates are stored as a DateTime? and I need to convert it to DateTime here
.Distinct()
.ToList();
The end result is a list containing a little over 2000 unique dates (all well and good). Per user requirements, I only need to collect the dates for the latest 90 records that would be created by the query (data is already sorted in the database, so no need to do that here).
My issue comes when I try to insert .Take(90)
between .Distinct()
and .ToList()
. The result is a list with only 13 records. I searched here and elsewhere to see if anyone else has had this issue, and haven't been able to find anything. Any ideas?
Props to @usr for helping with this. Here is the code that'll pull out 90 records, as desired:
var dateList =
Table1.Where(t1 => t1.column1.Contains(stringUsed)) //stringUsed is a parameter of the method containing this code
.Join(Table2, t1 => t1.columnName2, t2 => t2.columnName2,
(t1, t2) => new {t1, t2})
.Join(Table3, t1t2 => t1t2.t1.column3, t3 => t3.column3,
(t1t2, t3) => new {Date = t3.column4})
.Select(d => d.Date.Value) //Dates are stored as a DateTime? and I need to convert it to DateTime here
.Distinct()
.OrderByDescending(d => d)
.Take(90)
.ToList();
Apparently adding .OrderBy()
is what needed to be done. Thanks everyone.