Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IEnumerable<T> to List <T> Performance

I have a web service that returns List<SampleClass>. I take data from database using LINQ-to-SQL as IEnumerable<SampleClass>. I then convert IEnumerable<SampleClass> to List<SampleClass>.

LINQ-to-SQL operation performance is OK, but IEnumerable<SampleClass> to List<SampleClass> takes some time to do the operation. Are there any solutions to get best performance from IEnumerable<SampleClass> to List<SampleClass>?

I read more than 3000 records from my database.

Thank you

like image 875
Poorna Avatar asked Feb 01 '26 08:02

Poorna


1 Answers

IEnumerable to List takes some time to do the operation.

The reason you are getting the delay is because, when you do ToList, that is the time, when the actual query gets executed and fetches records from the database.

This is called Deferred execution.

var query = db.yourTable.Where(r=> r.ID > 10);
var List = query.ToList(); //this is where the actual query gets executed. 

When ever you iterate over the query using ToList, ToArray , Count() etc, that is when the actual query gets executed.

Are there any solutions to get best performance from IEnumerable to List? I read more than 3000 records from my database.

Without improving the query, No, you can't. But do you really need to fetch 3000 records, you may look into paging using Skip and Take

like image 115
Habib Avatar answered Feb 03 '26 20:02

Habib



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!