问题描述
所以基本上我有这种方法.
So basically i have this method.
public List<Customer> FilterCustomersByStatus(List<Customer> source, string status)
{
return (List<Customer>)source.Where(c => c.Status == status);
}
我向我抛出了一个无法投射的错误:
I throws me an error that it cannot cast:
为什么...?因为基础类型是相同的,所以Enumerable.Where在哪里创建WhereListIterator的新实例,如果是的话,为什么有人会这样做,因为那是不必要的性能和功能损失,因为我总是必须创建一个新列表(.ToList( ))
Why...? since the underlying type is the same, does the Enumerable.Where create a new instance of WhereListIterator and if so why would anyone do this, because thats an unnecessary loss of performance and functionality since i always have to create a new list (.ToList())
推荐答案
是的
因为它允许延迟流传输行为.如果Where
的使用者仅需要第一个或第二个条目,则不必筛选所有列表.这对于LINQ是正常的.
Because it allows lazy streaming behavior. Where
won't have to filter all the list if its consumer wants only first or second entry. This is normal for LINQ.
性能和功能损失"来自您的设计.过滤后不需要List<Customer>
,因为对其进行任何修改都是没有意义的.
That "loss of performance and functionality" comes from your design. You don't need List<Customer>
after filtering, because it's pointless to do any modifications on it.
更新:为什么要实施" 因为它是在IEnumerable
而不是IList
上实现的.因此,它看起来像IEnumerable
,听起来很像IEnumerable
.
Update: "why is it implemented so"Because it it implemented over IEnumerable
, not IList
. And thus it looks like IEnumerable
, it quacks like IEnumerable
.
此外,以这种方式实现它要容易得多.想象一下,您必须在IList
上写Where
.其中必须返回IList
.应该怎么办?返回原始列表的代理?您每次访问都会遭受巨大的性能损失.返回带有过滤项目的新列表?与Where().ToList()
相同.返回原始列表,但删除了所有不匹配的项目?这就是RemoveAll
的用途,为什么要使用另一种方法.
Besides, it's just so much easier to implement it this way. Imagine for a moment that you have to write Where
over IList
. Which has to return IList
. What should it do? Return a proxy over original list? You'll suffer huge performance penalties on every access. Return new list with filtered items? It'll be the same as doing Where().ToList()
. Return original list but with all non-matching items deleted? That's what RemoveAll
is for, why make another method.
记住,LINQ尝试发挥功能,并尝试将对象视为不可变对象.
And remember, LINQ tries to play functional, and tries to treat objects as immutables.
这篇关于来自List< MyType>的无效类型转换到IEnumerable< MyType>回到List< MyType> ;,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!