LINQ 是否适用于 IEnumerable? [英] Does LINQ work with IEnumerable?
问题描述
我有一个类实现了 IEnumerable
,但没有实现 IEnumerable
.我不能改变这个类,我不能用另一个类代替它.正如我从 MSDN 了解到的 如果类实现了 ,则可以使用 LINQIEnumerable
.我已经尝试使用 instance.ToQueryable()
,但它仍然没有启用 LINQ 方法.我确信这个类只能包含一种类型的实例,所以这个类可以实现 IEnumerable
,但它只是没有.那么如何使用 LINQ 表达式查询这个类呢?
I have a class that implements IEnumerable
, but doesn't implement IEnumerable<T>
. I can't change this class, and I can't use another class instead of it. As I've understood from MSDN LINQ can be used if class implements IEnumerable<T>
. I've tried using instance.ToQueryable()
, but it still doesn't enable LINQ methods. I know for sure that this class can contain instances of only one type, so the class could implement IEnumerable<T>
, but it just doesn't. So what can I do to query this class using LINQ expressions?
推荐答案
您可以使用 Cast
或 OfType
来获取通用版本一个完全支持 LINQ 的 IEnumerable.
You can use Cast<T>()
or OfType<T>
to get a generic version of an IEnumerable that fully supports LINQ.
例如
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>();
如果您的非泛型 IEnumerable
包含各种类型的对象并且您只对例如感兴趣.你可以做的字符串:
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>();
这篇关于LINQ 是否适用于 IEnumerable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!