为什么LINQ操作会丢失集合的静态类型?

soc*_*soc 1 c# linq collections types scala

无论我用作输入的集合类型,LINQ总是返回IEnumerable<MyType>而不是List<MyType>HashSet<MyType>.

MSDN教程:

int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// numQuery is an IEnumerable<int> <====== Why IEnumerable<int> instead of int[]?
var numQuery =
    from num in numbers
    where (num % 2) == 0
    select num;
Run Code Online (Sandbox Code Playgroud)

我想知道决定不保留集合类型(如元素类型)的原因是什么,而不是建议的解决方法.

我知道toArray,toDictionarytoList存在,这不是问题.

编辑:C#中的实现与Scala的不同之处在于如何在不覆盖各地的返回类型的情况下工作?

Bro*_*ass 7

Linq标准查询运算符是定义的IEnumerable<T>,而不是任何其他特定的集合类型.它适用于大多数集合,因为它们都实现了IEnumerable<T>.

这些标准查询运算符的输出是新的IEnumerable<T>- 如果要支持所有可用集合,则需要N个标准查询运算符的实现,而不仅仅是一个.

Linq的许多方面,如懒惰的评估,如果被迫工作,即a List<T>而不是a IEnumerable<T>.