Tolist vs Typed Tolist

Asked

Viewed 406 times

5

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

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

Take the example:

Note: The property PessoaId is of the whole type.

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

Same typical example:

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

Is there any difference in performance for example?

Doubt also extends to other methods, such as .ToArray().

2 answers

4

The normal is to use the 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 which type you want the list to be.

If that PessoaId is already a int it has no advantage to use it except to make it more explicit in the code. But let’s say that wanted to save in the list as object, then it would be necessary to do ToList<object>().

4


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

It only makes sense to use the typed method if you want to specify a different type than IEnumerable. Other than that, you don’t need to specify it.

If desired, the implementation of the method .ToList() is in the on the Microsoft website, which is this below:

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

Is there any difference in performance for example?

No, the generated code will be the same.


Translating the words of Jon Skeet:

For example, suppose you own a IEnumerable<string> and want to create a List<T>. If you want a List<string>, just use the .ToList(). If you want to use Covariance and get a List<object>, use the ToList<object>

See the example below:

IEnumerable<string> strings = new [] { "foo" };
List<string> stringList = strings.ToList();
List<object> objectList = strings.ToList<object>();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.