Consider the following piece of code, Here I can typecast IEnumerable<A>
to List<A>
, as that's what it contains internally, but when I use Select
to transform the same collection to IEnumerable<B>
, it is not List<B>
, which I can only achieve by calling ToList()
, which is a penalty in my actual code, due to millions records in the first collection. Is there a better way to achieve it, I wonder why List<A>
doesn't transform into List<B>
, if List is the underlying memory allocation
void Main()
{
A a = new A { Id = 1 };
IEnumerable<A> aList = new List<A> {a};
((aList as List<A>) != null); // True
var bList = aList.Select(x => new B { Id = x.Id});
((bList as List<B>) != null); // False
}
public class A
{
public int Id { get; set;}
}
public class B
{
public int Id { get; set; }
}
答案 0 :(得分:1)
您的bList
是IEnumerable<B>
,其中aList
的值尚未转换。例如,当您foreach
超过该列表或在其上调用.ToList()
时,就会发生转换。这是&#34;懒惰&#34;评论中提到的方面。
所以你的第二个测试是正确的:它是不是一个List<B>
。