Invalid cast from List to IEnumerable back to List, why?

后端 未结 5 1260
无人及你
无人及你 2021-01-13 11:02

So basically i have this method.

public List FilterCustomersByStatus(List source, string status)
{
    return (List

        
5条回答
  •  一整个雨季
    2021-01-13 11:33

    The difference between IEnumerable and IList is, the enumerable doesn't contain any data, it contains an iterator that goes through the data as you request the new one (for example, with a foreach loop). On the other hand, the list is a copy of the data. In your case, to create the List, ToList() method iterates through the entire data and adds them to a List object.

    Depending to the usage you are planning, both have advantages and disadvantages. For example, if you are planning to use the entire data more than once, you should go with the list, but if you are planning to use it once or you are planning to query it again using linq, enumerable should be your choice.

    Edit: The answer to the question why the return type of Where is WhereListIterator instead of List is, it's partly because how Linq works. For example, if you had another Where or another Linq statement following the first, the compiler would create a single query using the entire method chain, then return the iterator for the final query. On the other hand, if the first Where would return a List that would cause each Linq method in the chain execute separately on the data.

提交回复
热议问题