Problem getting minimum length using LINQ?

Here I get the minimum size of the text file inside the directory. But it gives 0as a minimum size. But there is no 0 kb file in this directory.

var queryList3Only= (from i in di.GetFiles("*.txt", SearchOption.AllDirectories)
                     select i.Length / 1024).Min();
dest.WriteLine(queryList3Only.ToString()+" Kb");

Any suggestion?

+3
source share
3 answers

you need to select doubles not int. if the file size is <1024, then you will end with a size of 0

var queryList3Only= (from i in di.GetFiles("*.txt", SearchOption.AllDirectories)
                     select (double)i.Length / 1024).Min();
+6
source

If you have files smaller than 1024 bytes in size, they will be displayed as zero, since your integer division will be truncated.

1023 / 1024 = 0

You may find that casting to doubles will give you an answer between 0 and 1.

+2
source

i.Lengthlong. When i.Lengthless than 1024, i.Length / 1024will return 0.

Use i.Length / 1024.0instead

+2
source

All Articles