In the following code foreach loop works fine, but when I try to use LINQ instead of using foreach it doesn’t work no exception no error.
This code is working :
public static IEnumerable<PatternInfo> LoadPatterns() {
var directoryInfo = new DirectoryInfo(PatternFullPath);
var dirs = directoryInfo.EnumerateDirectories();
var result = new List<PatternInfo>();
foreach (var info in dirs)
{
result.Add(new PatternInfo
{
PatternName = info.Name,
TemplateFileNames = GetTemplateFiles(info.FullName)
});
}
return result;
}
But this one not :
public static IEnumerable<PatternInfo> LoadPatterns() {
var directoryInfo = new DirectoryInfo(PatternFullPath);
var dirs = directoryInfo.EnumerateDirectories();
var patterns = dirs.Select(info => new PatternInfo {
PatternName = info.Name,
TemplateFileNames = GetTemplateFiles(info.FullName)
});
return patterns;
}
Any advice will be helpful.
The difference between the two is that in the first code sample you have a
List<PatternInfo>, all items in the list are populated already – then you return this list asIEnumerable<PatternInfo>.In the second example you have a
IEnumerable<PatternInfo>– this will only load the patterns when you iterate over the enumeration for the first time.If you want the second version to be equivalent (eager loading of the patterns) then add a
ToList():