Should i use .ToList().Distinct() or .Distinct().ToList()?

Viewed 235

When it comes to performance, should i use .ToList().Distinct() or .Distinct().ToList() ?

Both extension methods generate the same SQL query or not?

It seems that the second approach should perform better but is that true?

Are there any advantages or disadvantages of using one over another?

3 Answers

Short Answer: .Distinct().ToList()

Explain:

ToList: It converts an IEnumerable<T> to a List<T>, It's called Immediate execution. So you should filter all data in DB Server first instead of get all data then Distinct in "client-side"

It depends. If it is a query that is executed against a List<T> or a Dictionary<K,V> then the latter (Distinct().ToList()) would be preferrable.

The reason being, that if you do .ToList().Distinct(), Distinct() returns an IEnumerable that has to be executed again to get a real collection. In essence, you create two collections, but you would never use the first one.

There is a situation however where .ToList().Distinct() can be preferrable and that is if you are working with a Object-to-Relational mapper (see: EntityFramework) and you want to fetch all rows from a database table (maybe to populate a cache in the background or to use up less CPU on the database) and then do the .Distinct() operation locally.

Your mention of SQL suggests that your datasource is a DBContext of some kind.

In that situation, by definition, once you have done .ToList() all available data has been converted to objects in .NET Memory. Doing a .Distinct() after that can only run in .NET memory - it will run as if there is no database.

The SQL query for the above is definitely not the same as for .Distinct().ToList(), which will let the database do the DISTINCT operation.

To achieve the best performance, the best thing to do is .Distinct().ToList().

Related