I have the following code which works fine and I am getting the required details as expected. This data is passed on to the front end to be displayed in a grid.
public object Test(SearchGridParam obj)
{
List<GridModel> res =
(from data in _entity.TableNoTracking
where (string.IsNullOrWhiteSpace(obj.Criticality) || data.CRITICALITY.Equals(obj.Criticality))
&& (string.IsNullOrWhiteSpace(obj.Search)
|| (!string.IsNullOrWhiteSpace(data.DESCRIPTION) && data.DESCRIPTION.ToUpper().Contains(obj.Search.ToUpper()))
|| (!string.IsNullOrWhiteSpace(data.NUMBER) && data.NUMBER.ToUpper().Contains(obj.Search.ToUpper()))
)
select new GridModel
{
ID = data.ID,
NUMBER = data.NUMBER,
CRITICALITY = data.CRITICALITY,
WO_STATUS = data.WO_STATUS,
ASSET_NUMBER = data.ASSET_NUMBER,
DESCRIPTION = data.DESCRIPTION,
HOURS = data.HOURS,
START_DATE = data.START_DATE
})
.OrderByDescending(ord => ord.START_DATE)
.ToList(); //Gives 300+ records depending on the filters
int count = res.Count();
return new Result
{
Result = res.Skip(obj.Skip).Take(obj.Take), // fetching only 10
Count = count
};
}
Context
As per requirement:
- I need the Count after the "where" condition is applied. (I have achieved it using:
int count = res.Count();
) - In the final result set, I need only 10 records at a time. (Achieved using:
res.Skip(obj.Skip).Take(obj.Take)
) - I am getting the data from the database (dbContext).
Question
As you can see, I just need 10 records using skip & take. But, just to get the count, I am having to use ToList()
(which loads all data to the memory). Is there any other optimized way of doing it? OR is there any alternative approach to skip, take & count?
What I have tried
- I have tried the following to improve the performance, but it takes the same time (or sometimes more that
.ToList()
)
// *****code above is same*****
.OrderByDescending(ord => ord.START_DATE)
.AsQueryable();
int count = res.Count();
return new Result
{
Result = res.Skip(obj.Skip).Take(obj.Take).ToList(),
Count = count
};
Edit 1
I am fetching the data from Oracle DB