# Simplify 'if' condition

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...

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");

• Isn't Count faster than Any()? Maybe that wasn't your point though. – Anders Arpi Nov 23 '12 at 14:52
• 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.... – dreza Nov 23 '12 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.

• You could also do something like this: var smallFileNames = directory.Exists ? directory.GetFiles("*.csv").Select(i => i.FullName).ToList() : new List<string>(); – Jeff Vanzella Nov 20 '12 at 19:15
• But it would always create a list, even when not needed. – Amiram Korach Nov 20 '12 at 20:23
• 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. – Jeff Vanzella Nov 20 '12 at 22:08
• hidden relation between directory and fileName Thank you. I think it's good idea. – Chepene Nov 21 '12 at 6:40