Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.Take(100).ToList() vs. list.GetRange(0,100)

Tags:

c#

linq

List<AttendeeInfo> attendees = new List<AttendeeInfo>();
foreach ...
// Error: "There are too many target users in the email address array"
// for more than 100 attendees. So take the first 100 attendees only.
if(attendees.Count > 100) attendees = attendees.GetRange(0,100);
// or
if(attendees.Count > 100) attendees = attendees.Take(100).ToList();

Since I work on a list which is always longer than 100, and always take the first 100, the most obvious differences (Evaluation strategy, possibility to skip, throwing on errors) are not really interesting.

But perhaps you could shed some light on what exactly "Creates a shallow copy of a range of elements in the source List" means. It sounds really expensive, more so than Take, but is it?

like image 928
Alexander Avatar asked Sep 21 '15 09:09

Alexander


Video Answer


1 Answers

There is a minor between Take and GetRange. Take will evaluate lazily until you force it to evaulate into ToList(). This can change behavior.

Consider the pseudo code.

List<int> myList = new List<int>() {1,2,3,4,5,6};
IEnumerable<int> otherList = myList.Take(3);  // {1,2,3};
myList.RemoveRange(0,3);
// myList = {4, 5, 6}
// otherList = {4, 5, 6}

Now change this example to following code.

List<int> myList = new List<int>() {1,2,3,4,5,6};
IEnumerable<int> otherList = myList.Take(3).ToList();  // {1,2,3};
myList.RemoveRange(0,3);
// myList = {4, 5, 6}
// otherList = {1, 2, 3}

Doing ToList() can change the behavior of Take or GetRange depending upon what operations you are using next. It is always easier to use GetRange since it will not cause any unknown bugs.

Also GetRange is efficient.

like image 171
Manu Chandel Avatar answered Sep 18 '22 14:09

Manu Chandel