Home > Back-end >  Addition of numbers obtained in foreach in C#
Addition of numbers obtained in foreach in C#

Time:04-17

With the following code, I will receive the volume of all Windows hard disks separately

        foreach (var drive in DriveInfo.GetDrives())
        {
            int bb = Convert.ToInt32(drive.TotalSize / 1024 / 1024 / 1024);
        }

And this is what returns

100GB 500GB 2300GB

But I want to collect the numbers and hand them over But this is what I want 100GB 500GB 2300GB

2900GB

CodePudding user response:

This way you get the byte capacity of all your disks:

    int byteTotalCapacity = 0;
    foreach (var drive in DriveInfo.GetDrives())
    {
        byteTotalCapacity  = drive.TotalSize;
    }
    

if you want it in GB you must divide by (1024*1024)

CodePudding user response:

using System.Linq;
using System.IO;
using System;

public static class Drives
{
    public static long GetAllDriveSize()
    {
        return DriveInfo.GetDrives().Where(d => d.IsReady).Sum(d => d.TotalSize / 1024 / 1024 / 1024);
    }
}

Console.WriteLine(Drives.GetAllDriveSize());
Console.ReadLine();

//DriveInfo.GetDrives() - Get Drive list.
//Where(d => d.IsReady) - filters only drives(elements) that are ready otherwise will get exception when trying to get total size.
//Sum(d => d.TotalSize / 1024 / 1024 / 1024) - Sum each element / 1024 / 1024 / 1024

//d => ....  Is lambda expression (anonymous function). d is the parameter of the function and .... is the value returned by this function.

References
Lambda expressions
Linq - Where
Linq - Sum

  • Related