Search code examples
c#.nethard-drive

Addition of numbers obtained in foreach in C#


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


Solution

  • You can test/run this code on https://dotnetfiddle.net/27YcIp

    using System.Linq;
    using System.IO;
    using System;
    
    
    Console.WriteLine(Drives.GetAllDriveSizeA());
    Console.WriteLine(Drives.GetAllDriveSizeB());
    Console.WriteLine(Drives.GetAllDriveSizeC());
    Console.WriteLine(Drives.GetAllDriveSizeD());
    Console.ReadLine();
    
    public static class Drives
    {
        public static long GetAllDriveSizeA() // With Linq
        {
            return DriveInfo.GetDrives().Where(d => d.IsReady).Sum(d => d.TotalSize / 1024 / 1024 / 1024);
        }
    
        public static long GetAllDriveSizeB()
        {
            long total = 0;
            foreach (DriveInfo drive in DriveInfo.GetDrives()) //With foreach loop
            {
                if (drive.IsReady)
                {
                    total += drive.TotalSize / 1024 / 1024 / 1024;
                }
            }
            return total;
        }
    
        public static long GetAllDriveSizeC()//With for loop
        {
            long total = 0;
            DriveInfo[] drives = DriveInfo.GetDrives();
            for (int i = 0; i < drives.Length; i++)
            {
                if (drives[i].IsReady)
                {
                    total += drives[i].TotalSize / 1024 / 1024 / 1024;
                }
            }
            return total;
        }
    
        public static long GetAllDriveSizeD() //With List<T>.Foreach 
        {
            long total = 0;
            DriveInfo.GetDrives().ToList().ForEach(drive =>
            {
                if (drive.IsReady)
                {
                    total += drive.TotalSize / 1024 / 1024 / 1024;
                }
            });
            return total;
        }
    }
    
    
    //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.
    

    Output my PC

    1360
    1360
    1360
    1360
    

    References
    Lambda expressions
    Linq - Where
    Linq - Sum
    List.Foreach