Click here to Skip to main content
15,896,382 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi,

C#
List<int> idList = new List<int>() {1,2,3,4,5,7,8,9,-1};

//Option1
List<int> validIdList = idList.Where(x => x > 5).Select(x=> x).ToList();

//Option2
List<int> validIdList = idList.Where(x => x > 5).Select(x=> x).ToList<int>();


out of above which is better option? why?
I know ToList<int> is more type safe but when I am selecting integer value, then is it really necessary to use generic ToList<t>?

Thanks in advance,
Pushkar
Posted
Updated 9-May-15 21:34pm
v2

The both of the options use the same generic ToList method. In the first option the generic parameter is set implicitly to int because you work with an IEnumerable<int> collection.

 
Share this answer
 
v2
It's irrelevant: they generate the same code. In the first case, the type of the list is inferred from the IEnumerable returned by the Select method - in this case int.
In the second case, you are explicitly specifying that the list is of integers - which will only work if the IEnumerable the Select method returns is of int - otherwise, you get a compilation error:
Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<int>' to 'System.Linq.ParallelQuery<whatevertypeyouspecified>'</whatevertypeyouspecified></int>

I'd use the first version (and do)
 
Share this answer
 
Comments
Maciej Los 10-May-15 5:24am    
Unless OP wants to explicit conversion (from List<int>() to Listt<int>()) :laugh:
i think it is the same.
first just pick it up and store in list ( whatever type it is)
second the picked things must be only int

Cheer!
 
Share this answer
 
Hi,

If you taking a helicopter view then all are same.

but if you dig into details then you could found some difference between them in terms of performance

1st :
List<int> idList = new List<int>() {1,2,3,4,5,7,8,9,-1};


initialization of List<int> with pre-define list

2nd :
List<int> validIdList = idList.Where(x => x > 5).Select(x=> x).ToList();

Now you selecting specific values depending on criteria then create a new list with selected items with out any type casting as you know its already a List<int> so it will take little more time then pre-define list.

3rd :
List<int> validIdList = idList.Where(x => x > 5).Select(x=> x).ToList<int>();


Now in this statement you again selecting elements using some criteria and creating and new list using implicit casting to Int32 so it will take some more time then 2nd statement but its more type safe then 2nd but if you already know its a List<int> then why you need type cast.

Those are the basic difference in terms of performance, in terms of memory allocation in 1st it will allocate more memory the others.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900