ToList vs. Typed ToList

5

I was reviewing some methods of an ASP.NET MVC project and found some cases where only .ToList() is used and others where .ToList<type>() is used (where type is a type of object used in context).

Imagine that only with .ToList() would you already have a list with the type you need, why would you use a% typed%?

See the example:

Note: The ToList() property is an integer type.

var pessoasIds = db.Pessoa.Select(p => p.PessoaId).ToList();

Same typed example:

var pessoasIds = db.Pessoa.Select(p => p.PessoaId).ToList<int>();

Is there a difference in terms of performance for example?

Doubt also extends to other methods, such as PessoaId .

    
asked by anonymous 14.03.2017 / 13:07

2 answers

4

In fact, the two are the same, because the generated code will be the same.

It only makes sense to use the typed method if you want to specify a type other than IEnumerable . Other than that, you do not have to specify it.

If you want, the implementation of the .ToList() method is in the from Microsoft , which is this below:

public static List<TSource> ToList<TSource>(
    this IEnumerable<TSource> source
)
  

Is there a difference in terms of performance for example?

No, the generated code will be the same.


Translating the words from Jon Skeet

:

14.03.2017 / 14:02
4

The normal is to use ToList() , the compiler infers the type and everything works. But what if you want the list to be of a different type, compatible, of course, what to do? You have to specify what type you want the list to be.

If this PessoaId is already a int it has no advantage whatsoever to use it except to make it more explicit in the code. But let's say you wanted to keep the list as object , so you would have to ToList<object>() .

    
14.03.2017 / 13:59