LINQ 是否与 IEnumable 一起工作?

我有一个实现 IEnumerable但不实现 IEnumerable<T>的类。我不能更改这个类,也不能使用其他类来代替它。据我所知,从 MSDN 如果类实现 IEnumerable<T>,则可以使用 LINQ。我试过使用 instance.ToQueryable(),但它仍然不启用 LINQ 方法。我确信这个类只能包含一种类型的实例,所以这个类可以实现 IEnumerable<T>,但它就是不能。那么我该怎么做才能使用 LINQ 表达式来查询这个类呢?

61890 次浏览

Yes it can. You just need to use the Cast<T> function to get it converted to a typed IEnumerable<T>. For example:

IEnumerable e = ...;
IEnumerable<object> e2 = e.Cast<object>();

Now e2 is an IEnumerable<T> and can work with all LINQ functions.

You can use Cast<T>() or OfType<T> to get a generic version of an IEnumerable that fully supports LINQ.

Eg.

IEnumerable objects = ...;
IEnumerable<string> strings = objects.Cast<string>();

Or if you don't know what type it contains you can always do:

IEnumerable<object> e = objects.Cast<object>();

If your non-generic IEnumerable contains objects of various types and you are only interested in eg. the strings you can do:

IEnumerable<string> strings = objects.OfType<string>();

You can also use LINQ's query comprehension syntax, which casts to the type of the range variable (item in this example) if a type is specified:

IEnumerable list = new ArrayList { "dog", "cat" };


IEnumerable<string> result =
from string item in list
select item;


foreach (string s in result)
{
// InvalidCastException at runtime if element is not a string


Console.WriteLine(s);
}

The effect is identical to @JaredPar's solution; see 7.16.2.2: Explicit Range Variable Types in the C# language specification for details.