Skip to main content
 首页 » 编程设计

c#之这个 LINQ 查询会枚举整个枚举吗

2024年02月05日12findumars

我正在尝试为 ASP.NET 网站上传多个文件。因此,我有以下简化示例:

public ContentResult UploadFiles(IList<HttpPostedFileBase> files) 
{ 
    if (files == null || 
        !files.Any()) 
    { 
        // Nothing uploaded. 
        return Content("No files where uploaded."); 
    } 
 
    myService.UploadCsvFilesToDatabaseAsync(files.Select(x => x.InputStream)); 
 
    return Content("Success!"); 
} 

请注意:myService.UploadCsvFilesToDatabaseAsync(files.Select(x => x.InputStream)

我不想在此时 枚举文件......但稍后当我在该方法时。

那么,files.Select(x => x.InputStream) 此时 是否进行任何枚举?或者它只是传入一个新集合,其中包含每个输入流的开始,准备好被枚举。

澄清:我不想此时从文件中读取任何数据,但稍后在里面,那个方法。

请您参考如下方法:

So, does files.Select(x => x.InputStream) do any enumerating at this point ?

不,引用自Documentation

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach

因此,在您实际枚举它之前,它实际上不会处理列表。下面是一个简单的测试

        List<int> intlist = new List<int>() {1,2,3}; 
 
        var result = intlist.Select(x => x); 
 
        intlist.Add(12); 
 
        foreach (var item in result) 
        { 
            Console.WriteLine(item); 
        } 

这甚至会考虑在 LINQ 表达式之后添加的元素。如果它被预加载,它就不会包含元素 12。

结果:

1 
2 
3 
12 

更新:有关延迟执行和已执行的完整示例,请查看 this .NET fiddle example .