Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Object implement the IEnumerable interface C#?

Tags:

c#

linq

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.

like image 306
ckv Avatar asked Jul 26 '26 10:07

ckv


2 Answers

System.Array (which is what you're creating when using the Developer[] notation, Implements IEnumerable.

like image 116
Federico Berasategui Avatar answered Jul 28 '26 13:07

Federico Berasategui


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.

like image 43
p.s.w.g Avatar answered Jul 28 '26 13:07

p.s.w.g



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!