Invalid listing from <MyType> to IEnumerable <MyType> back to <MyType>, why?

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 get an error that cannot be executed:

Cannot pass an object of type "WhereListIterator`1 [AppDataAcces.Customer]" to enter "System.Collections.Generic.List`1 [AppDataAcces.Customer]".

Why...? since the base type is the same whether Enumerable.Where does the creation of a new instance of WhereListIterator, and if so, why do this because it is an extra loss of performance and functionality, since I always need to create a new list (.ToList ())

+5
source share
5 answers

set to Enumerable.Where creates a new instance WhereListIterator

Yes.

, -

. Where , . LINQ.

, (.ToList())

" " . List<Customer>, .

: " " IEnumerable, IList. , , IEnumerable, IEnumerable.

, . , Where IList. IList. ? - ? . ? , Where().ToList(). , ? RemoveAll, .

, LINQ .

+10

, ToList List<T>.

, Where , Where . IEnumerable, .

. , Where IEnumerable s ..

ToList List<T>, , -, .

+2

IEnumerable<TSource>, .ToList()

public List<Customer> FilterCustomersByStatus(List<Customer> source, string status)
{
    return source.Where(c => c.Status == status).ToList();//This will return a list of type customer
}
0

IEnumerable IList , , iterator, (, foreach). , - . List, ToList() List.

. , , , linq, .

Edit: The answer to the question of why the Where return type is WhereListIterator instead of List, this is partly because Linq works. For example, if you had a different Where statement or another Linq following the first, the compiler will create one request using the entire chain of methods, and then return an iterator for the final request. On the other hand, if the first Where returns a list, which will cause each Linq method in the chain to execute separately according to the data.

0
source

Try the following:

public List<Customer> FilterCustomersByStatus(List<Customer> source, string status)
{
    return source.Where(c => c.Status == status).ToList();
}
-1
source

All Articles