调用 .ToList() 时出现 IndexOutOfRange 异常

IndexOutOfRange Exception when calling .ToList()

我有一个名为 usages 的实体列表,我从中创建了一个 AdminUsage 类型实体的 IEnumerable,如下所示:

var models = usages.Select(u => new AdminUsage(u));

当我在 models 上调用 .ToList() 时,我收到一个 IndexOutOfRange 异常消息 "Index was outside the bounds of the array."

为什么会发生这种情况,我如何才能从我的原始列表 usages 中成功获得类型 AdminUsage 的列表?

编辑:好的,实际上超出范围的索引在 AdminUsage 构造函数中:

public AdminUsageModel(Usage usageDetails) { Title = usageDetails.UsageName[0] }

所以我修改后的问题是为什么异常只在调用 .ToList() 而不是在原来的 .Select() 上抛出?

why is the exception only thrown on the call .ToList() and not on the original .Select()?

因为 Select() 什么都不做,所以它是一个承诺。使用 ToList() 你实现了那个承诺,所以那是代码实际执行并抛出异常的时候。

另见 MSDN: IEnumerable<T>.Select():

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

另见 Deferred execution and eager evaluation, Trying to understand how linq/deferred execution works