LINQ是否与IEnumerable的工作? [英] Does LINQ work with IEnumerable?

查看:114
本文介绍了LINQ是否与IEnumerable的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类实现的IEnumerable ,但不执行的IEnumerable< T> 。我不能改变这个类的,我不能用它来代替另一个阶级。当我从MSDN LINQ了解可以使用,如果类实现的IEnumerable< T> 。我已经使用 instance.ToQueryable()试过了,但它仍然不会启用LINQ的方法。我确信,这个类只能包含一种类型的实例,因此类可以实施的IEnumerable< T> ,但它只是没有。所以,我能做些什么使用LINQ EX pressions来查询这个类?

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?

推荐答案

您可以使用演员LT; T&GT;() OfType&LT; T&GT; 来得到IEnumerable的一个通用版本,完全支持LINQ。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆