Convert IEnumerable<T> to List <T> Performance

c#, linq, linq-to-sql

Solution

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`

Problem

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

Original source