我不确定我是否完全理解以下示例的工作方式。简而言之,它来自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

最佳答案

TempProjectionItem是序列的元素类型...就像IEnumerable<int>(例如List<int>)是int值的序列,而int本身未实现IEnumerable一样。

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

这些都不是真正的集合-查询是延迟执行的-仅当您遍历数据时才对它进行评估(以names开头)。在query上进行迭代涉及在temp上进行迭代,然后在names上进行迭代。

09-26 23:20
查看更多