tags:

views:

66

answers:

2

I'm not sure I quite understand how the following example works. It's from C# 4.0 in a Nutshell.

class Program
{
    static void Main(string[] args)
    {
        string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };

        IEnumerable<TempProjectionItem> temp =
            from n in names
            select new TempProjectionItem
            {
                Original = n,
                Vowelless = n.Replace("a", "").Replace("e", "").Replace("i", "")
                             .Replace("o", "").Replace("u", "")
            };

        IEnumerable<string> query = from   item in temp
                                    where  item.Vowelless.Length > 2
                                    select item.Original;

        foreach (string item in query)
        {
            Console.WriteLine(item);
        }
    }

    class TempProjectionItem
    {
        public string Original;
        public string Vowelless;
    }
}

IEnumerable is an interface, isn't it? What kind of object is temp and query? Why does TempProjectionItem not need to implement IEnumerable?

+3  A: 

TempProjectionItem is the element type of the sequence... just like an IEnumerable<int> (such as a List<int>) is a sequence of int values without int itself implementing IEnumerable.

Note that there are two sequence interfaces: System.Collections.IEnumerable and System.Collections.Generic.IEnumerable<T>. Obviously the latter is generic, representing a sequence of a particular type. So temp is a sequence of TempProjectionItem elements, and query is a sequence of string elements.

Neither of these is really a collection as such - the queries are executed lazily - it's only evaluated (starting with names) when you iterate over the data. Iterating over query involves iterating over temp which then iterates over names.

Jon Skeet
A: 
IEnumerable is an interface, isn't it? 

Yes, it is. Actually in your code you are using IEnumerable<T> which is a generic interface.

What kind of object is temp and query?

In your code we can see temp is type of IEnumerable<TempProjectionItem>, while query is an IEnumerable<string>, both of which come from IEnumerable<T>.

Why does TempProjectionItem not need to implement IEnumerable?

TempProjectionItem is not IEnumerable, it's just an item of the IEnumerable<TempProjectionItem> which is a "container".

Danny Chen