[英]Casting List of type string to DeviceInfo[]
Is it possible to cast list of type string to DeviceInfo[]. 是否可以将字符串类型的列表强制转换为DeviceInfo []。 I am fetching list of logical drives on my computer and casting it to list to remove my system directory(My Operating System directory). 我正在获取计算机上逻辑驱动器的列表,并将其强制转换为列表以删除系统目录(“我的操作系统”目录)。 Now I want to cast that list back to DeviceInfo[] as I need to get the logical drive which has more space available. 现在,我想将该列表投射回DeviceInfo [],因为我需要获得具有更多可用空间的逻辑驱动器。
DriveInfo[] drive = DriveInfo.GetDrives();
List<string> list = drive.Select(x => x.RootDirectory.FullName).ToList();
list.Remove(Path.GetPathRoot(Environment.SystemDirectory).ToString());
Thank You. 谢谢。
You don't have to do Select()
您不必做Select()
DriveInfo[] driveFiltered = drive.Where(x => x.RootDirectory.FullName != Path.GetPathRoot(Environment.SystemDirectory).ToString()).ToArray();
EDIT: 编辑:
As @MarkFeldman pointed out, Path.GetPathRoot()
gets evaluated for all of the items on DriveInfo[]
. 正如@MarkFeldman指出的那样, Path.GetPathRoot()
DriveInfo[]
上的所有项目评估Path.GetPathRoot()
。 This won't make a difference for this particular case (unless you have like dozens of hard drives) but it might give you a bad LINQ habit :). 对于这种特殊情况,这不会有任何改变(除非您有数十个硬盘驱动器),但是这可能会给您带来不良的LINQ习惯:)。 The efficient way would be: 有效的方法是:
string systemDirectory = Path.GetPathRoot(Environment.SystemDirectory).ToString();
DriveInfo[] driveFiltered = drive.Where(x => x.RootDirectory.FullName != systemDirectory).ToArray();
Why not just use something like this? 为什么不只使用这样的东西?
List<DriveInfo> list = DriveInfo.GetDrives().Where(x => x.RootDirectory.FullName != Path.GetPathRoot(Environment.SystemDirectory).ToString()).ToList();
That would avoid converting to a string list, and preserve the type of the original DriveInfo[] array. 这样可以避免转换为字符串列表,并保留原始DriveInfo []数组的类型。
The code below will show the most space available; 下面的代码将显示最大可用空间;
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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.