A table Work
has three columns: ID
, Region
and Worker
.
And there are two DropDown lists.
DropDown A: Select and filter the Region
, is bound to region
with data regions
DropDown B: Select and filter the Worker
, is bound to worker
with data workers
The flow: user selects region, then selects worker of that region
Initialize:
List<Work> works = new();
works = GetWorks(); //get all the records from the table
List<string> regions = new();
List<string> workers = new();
regions = works.Select(w=>w.region).Distinct().ToList();
When the user selects a region
workers = works.Where(w=>w.Region == region).Select(w=>w.worker).Distinct().ToList();
However, it would be incredibly slow when there are thousands of records.
How can I achieve this more efficently? Thanks!
2
Answers
It seems like
GetWorks
might be returning aList
or anIEnumerable
. The issue here is that loading all those data into memory can be problematic. Essentially, the solution involves delegating the work to the database: makeGetWorks
return anIQueryable
. This way, when you executeworks.select(w => w.region).Distinct()
, that operation will be performed in the database. The same goes forworks.select(w => w.region).Distinct()
. You can achieve this only if you’re working inBlazorServer
.If you are working in Blazor-WASM, you’ll need to expose the services
GetRegions
andGetWorkers
.Bonus track: Normalize database and create
Region
model.I think that your program is slow because the
GetWorks()
returns aList<Work>
.Keep in mind that using Linq on a List, you are doing all the work on the machine. You can try refactoring your code exposing an
IQueryable
if you are using Entity Framework (even if is not a best practice).Or you could call the
GetWorks
with the filters and delegate the work to the database.