patterncsharpModerate
Indentation on a long (ish) linq chain
Viewed 0 times
linqlongindentationishchain
Problem
I have some code that loops through directories named for years (e.g.
or
or
or
/2011/, /2012/ etc) which each contain files whose names end with dates in the "yyyyMMdd" format, and builds a list of all the dates in all the directories. But what is the best way to indent this, nothing I've tried is readable:files = files.Union(
Directory.GetFiles(year)
.Select(d => DateTime.ParseExact(
Path.GetFileNameWithoutExtension(d)
.Substring(
Path.GetFileNameWithoutExtension(d)
.Length - 8),
"yyyyMMdd",
null))).ToList();or
files = files.Union(Directory.GetFiles(year)
.Select(d => DateTime.ParseExact(
Path.GetFileNameWithoutExtension(d).Substring(
Path.GetFileNameWithoutExtension(d).Length - 8),
"yyyyMMdd",
null)
)
).ToList();or
files = files.Union(Directory.GetFiles(year)
.Select(d => DateTime.ParseExact(
Path.GetFileNameWithoutExtension(d).Substring(
Path.GetFileNameWithoutExtension(d).Length - 8),
"yyyyMMdd",
null))).ToList();or
files = files.Union(Directory.GetFiles(year).Select(d => DateTime.ParseExact(
Path.GetFileNameWithoutExtension(d).Substring(
Path.GetFileNameWithoutExtension(d).Length - 8),
"yyyyMMdd", null))).ToList();Solution
I would consider refactoring the
Where
Either way, no matter how you indent it now, the method extraction of
.Select call to do this:files = files.Union(Directory.GetFiles(year).Select(d => GetTimeForFile(d))).ToList();Where
GetTimeForFile is a method with the following content:DateTime GetTimeForFile(String fileName)
{
var noExtName = Path.GetFileNameWithoutExtension(fileName);
return DateTime.ParseExact(noExtName.Substring(noExtName.Length - 8),
"yyyyMMdd", null);
}Either way, no matter how you indent it now, the method extraction of
GetTimeForFile makes it significantly more readable.Code Snippets
files = files.Union(Directory.GetFiles(year).Select(d => GetTimeForFile(d))).ToList();DateTime GetTimeForFile(String fileName)
{
var noExtName = Path.GetFileNameWithoutExtension(fileName);
return DateTime.ParseExact(noExtName.Substring(noExtName.Length - 8),
"yyyyMMdd", null);
}Context
StackExchange Code Review Q#64358, answer score: 10
Revisions (0)
No revisions yet.