Search code examples
c#linq

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


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?


Solution

  • The only difference is that List.GetRange is more efficient than Take(n).ToList() since it already knows the size of the new list whereas the LINQ methods don't know it's size.

    So ToList enumerates the sequence and adds the items to a new list with a doubling algorithm increasing the backing array consecutively. List.GetRange can create the proper list with the right initial size beforehand and then uses Array.Copy to copy the subset of the source list into the new list [source].