skip to Main Content

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


  1. It seems like GetWorks might be returning a List or an IEnumerable. The issue here is that loading all those data into memory can be problematic. Essentially, the solution involves delegating the work to the database: make GetWorks return an IQueryable. This way, when you execute works.select(w => w.region).Distinct(), that operation will be performed in the database. The same goes for works.select(w => w.region).Distinct(). You can achieve this only if you’re working in BlazorServer.

    If you are working in Blazor-WASM, you’ll need to expose the services GetRegions and GetWorkers.

    Bonus track: Normalize database and create Region model.

    Login or Signup to reply.
  2. I think that your program is slow because the GetWorks() returns a List<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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search