简体   繁体   English

C# 为什么 IEnumerable 和 IEnumerable.ToList() 打印它们的结果是不同的?

[英]C# Why IEnumerable and IEnumerable.ToList() print their result is difference?

I get the sequence number 0 ~ 2 with IEnumerable and when I print the result.我用 IEnumerable 得到序列号 0 ~ 2,当我打印结果时。 The IEnumerable and IEnumerable.ToList() result is difference. IEnumerableIEnumerable.ToList()结果是不同的。

void Main()
{
    var numbers = GetNumbers();
    Print(numbers); 
    /*  
    Return: 0
    Print: 0
    Return: 1
    Print: 1
    Return: 2
    Print: 2
    Return: 0
    Return: 1
    Return: 2
    Total: 3
    */
    
    Print(numbers.ToList());
    /*
    Return: 0
    Return: 1
    Return: 2
    Print: 0
    Print: 1
    Print: 2
    Total: 3    
    */
}

void Print(IEnumerable<int> numbers) {
    foreach(var number in numbers) 
    {
        Console.WriteLine($"Print: {number}");
    }   
    Console.WriteLine($"Total: {numbers.Count()}");
}
 
IEnumerable<int> GetNumbers()
{ 
    return Enumerable.Range(0, 3)
        .Select(n =>
        {
            Console.WriteLine($"Return: {n}");
            return n;
        });
}

Seems the pure IEnumerable the linq Select function is call twice when execute the IEnumerable.Count() .执行IEnumerable.Count()时,似乎纯 IEnumerable linq Select function 被调用两次。

What happened to this?这是怎么回事?

When you call numbers.Count() , you're enumerating the IEnumerable again.当您调用numbers.Count()时,您将再次枚举IEnumerable Because the IEnumerable is enumerated twice, the Return lines are each printed twice.因为 IEnumerable 被枚举了两次,所以 Return 行分别打印了两次。

The list conversion enumerates the IEnumerable to build the list, but after that, only the resulting List<int> is used by Print .列表转换枚举IEnumerable来构建列表,但之后, Print仅使用生成的List<int> When .Count() is called on the List, which just returns the built-in Count property of List<int> and doesn't enumerate anything.当在 List 上调用.Count()时,它只返回List<int>的内置Count属性并且不枚举任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM