首页 > 解决方案 > as List<> 与 ToList() 之间的区别

问题描述

我有一个字符串集合作为 Enumerable(例如,假设它是对集合进行一些 linq 查询的结果)。

IEnumerable<string> myStrings;

以下有什么区别

一个。

result = myStrings as List<string>;

湾。

result = myStrings.ToList();

一个比另一个更有效吗?选项 b 会改变 myStrings 本身吗?

标签: c#

解决方案


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);
        }

推荐阅读