In Linq to object, we can often easily query a variety of sets, such as List <T> generics, mainly because they all implement System. collections. generic. the IEnumerable <T> interface can complete related query operations, but not all classes have implemented the above interfaces, such as System. collections. arrayList, you can solve it in the following three ways.
I. OfType Operator
First, let's look at its signature public static IEnumerable <TResult> OfType <TResult> (this IEnumerable source) to filter IEnumerable elements based on the specified type. If source is null, ArgumentNullException is returned.
Var q = cars. OfType <Car> (). Where (c => c. Doors = 2 );
Ii. Cast forced conversion
From the signature of Cast, we can know that it can return IEnumerable <T>,
Public static IEnumerable <T> Cast <T> (this IEnumerable source)
However, if the type to be converted cannot be converted to T, Invalid-
CastException exception. If it is null, It is NullReferenceException. The code above is rewritten:
Var q = from c in cars. Cast <Car>
Where c. Doors = 2
Select new {c. Name}
Iii. Clear Type Definitions
Define the query type in from, as shown in figure
Var q = from Car c in cars
Where c. Doors = 2
Select new {c. Name}