How can I simplify this code?
if (directory.Exists)
{
smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
if(smallFileNames.Count == 0)
smallFileNames = DivideIntoFiles(fileName);
}
else
smallFileNames = DivideIntoFiles(fileName);
I confused by identical lines...
2 Answers 2
Jumping in after the horse has bolted with a very minor different approach (using Any rather than Count and null).
IEnumerable<string> GetSmallFileNames(Directory directory, string fileName, string filter)
{
var smallFileNames = new List<string>();
if (directory.Exists)
{
smallFileNames = directory.GetFiles(filter).Select(i => i.FullName);
}
return smallFileNames.Any() ? smallFileNames : DivideIntoFiles(fileName);
}
Then used such as
IEnumerable<string> smallFileNames = GetSmallFileNames(directory, fileName, "*.csv");
-
\$\begingroup\$ Isn't
Count
faster thanAny()
? Maybe that wasn't your point though. \$\endgroup\$Anders Arpi– Anders Arpi2012年11月23日 14:52:20 +00:00Commented Nov 23, 2012 at 14:52 -
\$\begingroup\$ Yes it probably is. But I would think the speed is actually so small that in this case it's irrelevant. Also people often mix .Count with .Count() which are subtly different. So .Any() just removes that confusion.... \$\endgroup\$dreza– dreza2012年11月23日 18:39:49 +00:00Commented Nov 23, 2012 at 18:39
...and you could simplify the second conditional by initializing smallFileNames
:
List<string> smallFileNames = new List<string>
if (directory.Exists)
{
smallFileNames = directory.GetFiles("*.csv").Select(i => i.FullName).ToList();
}
if (smallFileNames.Count == 0)
smallFileNames = DivideIntoFiles(fileName);
However, the whole logic seems unclear to me: there seems to be a hidden relation between directory
and fileName
. I would consider reviewing the surrounding code also.
-
\$\begingroup\$ You could also do something like this: var smallFileNames = directory.Exists ? directory.GetFiles("*.csv").Select(i => i.FullName).ToList() : new List<string>(); \$\endgroup\$Jeff Vanzella– Jeff Vanzella2012年11月20日 19:15:42 +00:00Commented Nov 20, 2012 at 19:15
-
\$\begingroup\$ But it would always create a list, even when not needed. \$\endgroup\$Amiram Korach– Amiram Korach2012年11月20日 20:23:52 +00:00Commented Nov 20, 2012 at 20:23
-
2\$\begingroup\$ I'm a big fan of always creating a list. Takes out the if (list == null) checks every time you want to use it. An empty list is just that, empty, so an iteration or check if there are values will fail if there are any. \$\endgroup\$Jeff Vanzella– Jeff Vanzella2012年11月20日 22:08:07 +00:00Commented Nov 20, 2012 at 22:08
-
\$\begingroup\$
hidden relation between directory and fileName
Thank you. I think it's good idea. \$\endgroup\$Chepene– Chepene2012年11月21日 06:40:57 +00:00Commented Nov 21, 2012 at 6:40