c# - as List<> 与 ToList() 之间的区别
问题描述
我有一个字符串集合作为 Enumerable(例如,假设它是对集合进行一些 linq 查询的结果)。
IEnumerable<string> myStrings;
以下有什么区别
一个。
result = myStrings as List<string>;
湾。
result = myStrings.ToList();
一个比另一个更有效吗?选项 b 会改变 myStrings 本身吗?
解决方案
Option a - result=myStrings as List<string>
is a safe way to typecast and know whether a given type contains List<string>
internally, there's no extra memory allocation, since it's typecasting it can be be done on any type / object. If the typecasting fails then result is null
, no exception, which might come if you try (List<string>) myStrings
instead.
Infact even better approach - is
operator, myStrings is List<string> result
(Called as Pattern matching is expressions) which provides boolean result and if true, it leads to valid value inside result variable (is
operator is there for quite sometime, but using variable result
for pattern matching which spans beyond the if loop and can be used in the logic thereafter is a C# 7.1 feature
Compared to this:
Option b - result=myStrings.ToList()
is extension method call on a IEnumerable<T>
, which allocates and creates new List<T>
data structure. This is always an extra allocation of memory. Following is the source code for the Enumerable.ToList()
call, link
public static List<TSource> ToList<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return new List<TSource>(source);
}
推荐阅读
- scala - 如何改进 Spark Scala 中 Oracle 表的卸载
- google-signin - 我应该使用 GoogleIdToken (jwt) 还是将其替换为另一个服务器发布的 jwt?还有关于客户 ID(“aud”)的问题
- javascript - Carto v4 + StoryMap - 如何将 Carto 图层标记数据链接到 StoryMap 场景
- java - 使用 Spring Security 调用“/authenticate”api 时访问被拒绝
- yii2 - 哪个 gridview 正在执行搜索?
- jsf - Primefaces FileUpload:处理防火墙错误阻止上传
- r - 在 R 中组合 2 个箱形图
- php - Codeingiter 4:“没有要更新的数据”异常
- visual-studio-code - 远程服务器上 VSCode 中的 Jupyter
- c# - asp:BoundField DataField 和 asp:BoundColumn Datafield 有什么区别