Re: FileInfo filter by size
I am not a fan of Linq. Instead just loop:
Code:
List<FileInfo> sizeFiltered = new List<FileInfo>();
foreach(FileInfo f in files)
{
if( f.Length >= lowerBound && f.Length >= upperBound )
sizeFiltered.Append(f);
}
Probably though your compiler is angry because Where is returning an IEnumerable<FileInfo>, not a FileInfo[] (??). You can probably call .ToArray() (or maybe .ToArray<FileInfo>() -- not sure) and get your Linq query to work. Elsewise, post the error message.
Re: FileInfo filter by size
Okay my compiler isn't angry any more but I'm having a bug when trying to display the contents of the list
I'm trying to receive an input number from the user and then displaying information about files that are within 1 mb of that chosen size. My code is below and it runs, but when I try entering a value of 1, I receive some results where the size is greater than 1 mb difference. if anyone can spot the reason for this in my code it would be greatly appreciated
Code:
int mb = 1048576;
int userSize = 0;
bool sizeIsNumber = int.TryParse(Console.ReadLine(), out userSize);
while (sizeIsNumber == false || userSize < 0)
{
Console.Clear();
Console.WriteLine("That is an invalid selection, please enter a whole number greater than 0");
sizeIsNumber = int.TryParse(Console.ReadLine(), out userSize);
}
int lowerBound = userSize - mb;
int upperBound = userSize + mb;
if (lowerBound < 0)
{
lowerBound = 0;
}
List<FileInfo> sizeFiltered = new List<FileInfo>();
foreach (FileInfo f in fileArray)
{
if (f.Length >= lowerBound && f.Length <= upperBound)
{
sizeFiltered.Add(f);
}
}
for (int i = 0; i < sizeFiltered.Count; i++)
{
Console.Write("{0}. ", i + 1);
Console.Write(fileArray[i].Name);
Console.Write(" ({0})", fileArray[i].Length);
Console.WriteLine();
}
Re: FileInfo filter by size
Code:
for (int i = 0; i < sizeFiltered.Count; i++)
{
Console.Write("{0}. ", i + 1);
Console.Write(sizeFiltered[i].Name);
Console.Write(" ({0})", sizeFiltered[i].Length);
Console.WriteLine();
}
N.B., you can do this in one statement instead of four:
Code:
Console.WriteLine("{0}. {1} {2}", (i+1), sizeFiltered[i].Name, sizeFiltered[i].Length);
Re: FileInfo filter by size
oh wow I feel dumb haha. Thanks very much
Re: FileInfo filter by size
An easy mistake to make! As I learned when programming in assembly (for which there was no debugger I liked): code review - just re-reading through your own code - is the single most powerful debugging tool you have at your disposal!