bala3569
bala3569

Reputation: 11010

Problem in getting Minimum length using LINQ?

Here i am retrieving minimum size of a text file inside a directory.But it gives 0 as a minimum size.But there is no 0 kb file inside that directory.

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

Any Suggestion?

Upvotes: 3

Views: 224

Answers (3)

Stecya
Stecya

Reputation: 23266

you need to select doubles not int's. if filesize is < 1024 then you will end with size 0

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

Upvotes: 6

Alex Aza
Alex Aza

Reputation: 78457

i.Length is long. When i.Length is less than 1024, i.Length / 1024 will return 0.

Use i.Length / 1024.0 instead

Upvotes: 2

Colin Mackay
Colin Mackay

Reputation: 19175

If you have any files less that 1024 bytes then they will appear as zero as your integer division will be truncated.

1023 / 1024 = 0

You may find casting the values to doubles will get you an answer between 0 and 1.

Upvotes: 2

Related Questions