list.Take(100).ToList()与list.GetRange(0,100) [英] list.Take(100).ToList() vs. list.GetRange(0,100)

查看:491
本文介绍了list.Take(100).ToList()与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();

由于我处理的列表总是大于100,并且总是采用前100,所以最明显的差异(评估策略,跳过的可能性,抛出错误)并不是很有趣.

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.

但是也许您可以确切地理解在源列表中创建一系列元素的浅表副本"的含义.听起来确实很贵,比Take还要贵,但是吗?

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?

推荐答案

唯一的区别是

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.

因此 ToList 枚举序列并添加项将数据加倍,并通过加倍算法连续增加后备数组. List.GetRange可以事先使用正确的初始大小创建正确的列表,然后使用来源].

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].

这篇关于list.Take(100).ToList()与list.GetRange(0,100)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆