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. 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
The sample code is taken from LINQ in Microsoft .NET Framework Book.
System.Array (which is what you're creating when using the Developer[] notation, Implements 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).
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. So you can can definitely use foreach on the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With