Home > Mobile >  Should I convert IQueryable to list first if I need to use it multiple times later?
Should I convert IQueryable to list first if I need to use it multiple times later?

Time:11-20

I'm new to C#. Have a question about IQueryable.

From what I understand IQueryable queries the database every time it gets called. In my case, I need to put the IQueryable inside a for each loop with more than 50k of loops, so it will be good to convert it to a list first to reduce database calls? Or is there any other good approach? Thanks

CodePudding user response:

Yes it probably is querying the database every time you read through it. You probably don't want to do that.

What do you mean 50k loops?

If you have 50k database records you are reading through in a loop, you should probably alter the database query to select the aggregate data you want. The database will be more efficient at giving you what you want, instead of processing 50k records in your code.

CodePudding user response:

The advantage of IQueryable is you can filter what you want before the database call is made. Then the backend code has just what you need. Not the junk data. Did you mean you are iterating 50K times and calling the same query?

Can't you get what you need from DB with IQueryable(one database call), and then loop or do whatever from the backend code with the data you have?

  • Related