.net LINQ 是否适用于 IEnumerable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7757365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does LINQ work with IEnumerable?
提问by Bogdan Verbenets
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?
我有一个实现 的类IEnumerable,但没有实现IEnumerable<T>。我不能改变这个类,我不能用另一个类来代替它。正如我从 MSDN 中了解到的,如果类实现了 LINQ,则可以使用IEnumerable<T>. 我试过使用instance.ToQueryable(),但它仍然没有启用 LINQ 方法。我确信这个类只能包含一种类型的实例,所以这个类可以实现IEnumerable<T>,但它只是没有。那么如何使用 LINQ 表达式查询这个类呢?
回答by DeCaf
You can use Cast<T>()or OfType<T>to get a generic version of an IEnumerable that fully supports LINQ.
您可以使用Cast<T>()或OfType<T>获取完全支持 LINQ 的 IEnumerable 的通用版本。
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 IEnumerablecontains objects of various types and you are only interested in eg. the strings you can do:
如果您的非泛型IEnumerable包含各种类型的对象并且您只对例如感兴趣。你可以做的字符串:
IEnumerable<string> strings = objects.OfType<string>();
回答by JaredPar
Yes it can. You just need to use the Cast<T>function to get it converted to a typed IEnumerable<T>. For example:
是的,它可以。您只需要使用该Cast<T>函数将其转换为类型化的IEnumerable<T>. 例如:
IEnumerable e = ...;
IEnumerable<object> e2 = e.Cast<object>();
Now e2is an IEnumerable<T>and can work with all LINQ functions.
现在e2是一个IEnumerable<T>并且可以使用所有 LINQ 函数。
回答by TrueWill
You can also use LINQ's query comprehension syntax, which casts to the type of the range variable (itemin this example) if a type is specified:
您还可以使用 LINQ 的查询理解语法,item如果指定了类型,它会转换为范围变量的类型(在本例中):
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 Typesin the C# language specification for details.
效果与@JaredPar 的解决方案相同;有关详细信息,请参阅C# 语言规范中的7.16.2.2:显式范围变量类型。

