2010-08-13 30 views
2

我不知道我非常理解下面的例子是如何工作的。它来自于C#4.0,在果壳中。C#LINQ/Object Initializers来自C#4.0的简单例子

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是一个接口,不是吗?什么样的对象是tempquery?为什么TempProjectionItem不需要执行IEnumerable

回答

3

TempProjectionItem元件型序列的...就像一个IEnumerable<int>(如List<int>)是int值的序列,而不int本身实施IEnumerable

请注意,有两个序列接口:System.Collections.IEnumerableSystem.Collections.Generic.IEnumerable<T>。显然后者是通用的,表示特定类型的序列。所以tempTempProjectionItem元素的序列,querystring元素的序列。

这些都不是真正的集合 - 查询是懒惰地执行的 - 它只在迭代数据时才被评估(从names开始)。遍历query涉及迭代temp,然后迭代names

0
IEnumerable is an interface, isn't it? 

是的。实际上,在您的代码中,您使用的是通用接口IEnumerable<T>

What kind of object is temp and query? 

在你的代码中,我们可以看到温度是IEnumerable<TempProjectionItem>类型,而查询是一个IEnumerable<string>,这两个来自IEnumerable<T>

Why does TempProjectionItem not need to implement IEnumerable? 

TempProjectionItem不是IEnumerable的,它只是IEnumerable<TempProjectionItem>这是一个“容器”的项目。