[英]Does Object implement the IEnumerable interface C#?
Say I have the following code: 说我有以下代码:
using System;
using System.Linq;
using System.Collections.Generic;
public class Developer
{
public string Name;
public string Language;
public int Age;
}
class App {
static void Main() {
Developer[] developers = new Developer[] {
new Developer {Name = "Paolo", Language = "C#"},
new Developer {Name = "Marco", Language = "C#"},
new Developer {Name = "Frank", Language = "VB.NET"}};
var developersUsingCSharp = from d in developers
where d.Language == "C#"
select d.Name;
foreach (var item in developersUsingCSharp) {
Console.WriteLine(item);
}
}
}
I have not explicitly implemented the IEnumerable<T>
interface. 我尚未明确实现
IEnumerable<T>
接口。 My question is the from clause will take instances of types that implement the IEnumerable interface, but in this case it is a user defined type of Developer class 我的问题是from子句将采用实现IEnumerable接口的类型的实例,但在这种情况下,它是用户定义的Developer类类型
The sample code is taken from LINQ in Microsoft .NET Framework Book. 该示例代码取自Microsoft .NET Framework Book中的LINQ。
System.Array
(这是使用Developer[]
表示法时要创建的,实现IEnumerable
。
By virtue of the fact that your assigning the variable developersUsingCSharp
to the result of a linq query, it is of type IEnumerable<string>
(it would be an IQueryable<string>
if this was a entity framework query or something similar). 由于您已将变量
developersUsingCSharp
分配给linq查询的结果,因此它的类型为IEnumerable<string>
(如果这是实体框架查询或类似的东西,则为IQueryable<string>
)。
Perhaps it's hard to analyze exactly what's happening with the query syntax. 也许很难准确分析查询语法发生了什么。 The query:
查询:
var developersUsingCSharp =
from d in developers
where d.Language == "C#"
select d.Name;
Is equivalent to the fluent syntax: 等效于流利的语法:
var developersUsingCSharp =
developers.Where(d => d.Language == "C#")
.Select(d => d.Name);
The Linq Select
and Where
extension methods both accept IEnumerable<T>
and return IEnumerable<T>
as a result. Linq
Select
和Where
扩展方法都接受IEnumerable<T>
并返回IEnumerable<T>
作为结果。 So you can can definitely use foreach
on the result. 因此,您绝对可以在结果上使用
foreach
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.