How can I simplify this? I am trying to get the count of Excel files from a directory and subdirectories based on their size. I have at least 10 different groupings.
var queryList2Only = from i in di.GetFiles("*.xls", SearchOption.TopDirectoryOnly)
.Where(f => f.Length <= 5120)
select i.Length;
if (queryList2Only.Any())
{
dest.WriteLine("Excel File <= 5 KB");
dest.WriteLine(queryList2Only.Count());
dest.WriteLine("");
}
var queryList3Only = from i in di.GetFiles("*.xls", SearchOption.TopDirectoryOnly)
.Where(f => f.Length > 5120 && f.Length <= 10240)
select i.Length;
if (queryList3Only.Any())
{
dest.WriteLine("Excel File > 5 KB and <= 10 KB");
dest.WriteLine(queryList3Only.Count());
dest.WriteLine("");
EDIT:
I need this
<= 5 KB,> 5 KB and <= 10 KB,> 10 KB and <= 20 KB,> 20 KB and <= 100 KB,> 100 KB and <= 1000 KB,> 1000 KB and <=5 MB,> 5 MB and <=10 MB,> 10 MB and <=20 MB,> 20 MB and <=50 MB,> 50 MB and <=100 MB
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo Folder = new DirectoryInfo(textBox1.Text);
var _logFolderPath4 = Path.Combine(textBox1.Text.Trim(), "log");
if (Folder.Exists)
if (!Directory.Exists(_logFolderPath4))
Directory.CreateDirectory(_logFolderPath4);
DirectoryInfo di = new DirectoryInfo(@"D:\Material\");
bool time = false;
using (var dest = File.AppendText(Path.Combine(_logFolderPath4, "Excel.txt")))
{
if (!time)
{
dest.WriteLine("---------------------" + DateTime.Now + "---------------------");
dest.WriteLine("");
time = true;
}
CountFiles(dest, di, @"*.txt");
}
}
You don’t necessarily need LINQ for this. It would be more efficient for you to just loop through it. Though Rup’s solution is a great use of LINQ here.
Here’s a more complete version tailored for exactly what you want to do.