簡體   English   中英

將類型字符串轉換為DeviceInfo []

[英]Casting List of type string to DeviceInfo[]

是否可以將字符串類型的列表強制轉換為DeviceInfo []。 我正在獲取計算機上邏輯驅動器的列表,並將其強制轉換為列表以刪除系統目錄(“我的操作系統”目錄)。 現在,我想將該列表投射回DeviceInfo [],因為我需要獲得具有更多可用空間的邏輯驅動器。

DriveInfo[] drive = DriveInfo.GetDrives();
List<string> list = drive.Select(x => x.RootDirectory.FullName).ToList();
list.Remove(Path.GetPathRoot(Environment.SystemDirectory).ToString());

謝謝。

您不必做Select()

DriveInfo[] driveFiltered = drive.Where(x => x.RootDirectory.FullName != Path.GetPathRoot(Environment.SystemDirectory).ToString()).ToArray();

編輯:

正如@MarkFeldman指出的那樣, Path.GetPathRoot() DriveInfo[]上的所有項目評估Path.GetPathRoot() 對於這種特殊情況,這不會有任何改變(除非您有數十個硬盤驅動器),但是這可能會給您帶來不良的LINQ習慣:)。 有效的方法是:

string systemDirectory = Path.GetPathRoot(Environment.SystemDirectory).ToString();
DriveInfo[] driveFiltered = drive.Where(x => x.RootDirectory.FullName != systemDirectory).ToArray();

為什么不只使用這樣的東西?

List<DriveInfo> list = DriveInfo.GetDrives().Where(x => x.RootDirectory.FullName != Path.GetPathRoot(Environment.SystemDirectory).ToString()).ToList();

這樣可以避免轉換為字符串列表,並保留原始DriveInfo []數組的類型。

下面的代碼將顯示最大可用空間;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication11
{
    class Program
    {

        static void Main(string[] args)
        {
            long FreeSize = 0;
            DriveInfo[] drive = DriveInfo.GetDrives().Where(x =>
            {
                if (x.RootDirectory.FullName != Path.GetPathRoot(Environment.SystemDirectory).ToString() && x.AvailableFreeSpace >= FreeSize)
                {
                    FreeSize = x.AvailableFreeSpace; 
                    Console.WriteLine("{0}Size:{1}", x.Name, x.AvailableFreeSpace);
                    return true;
                }
                else
                {
                    return false;
                }
            }).ToArray();

            Console.ReadLine();

        }
    }
}

屏幕截圖1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM