一个蛮复杂的LINQ表达式
最近写了这么一个方法:
//返回结果大致为:AAGP30PMDRVS56NK public string GetUsbDiskSnViaDriveLetter(string strUsbDiskDriveLetter) { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition"); foreach (ManagementObject dm in searcher.Get()) { //dm["Dependent"] 大致为:\\JIANG-PC\root\cimv2:Win32_LogicalDisk.DeviceID="H:" string strDriveLetter = getValueInQuotes(dm["Dependent"].ToString()); if (strDriveLetter == strUsbDiskDriveLetter) { //dm["Antecedent"] 大致为:\\JIANG-PC\root\cimv2:Win32_DiskPartition.DeviceID="Disk #1, Partition #0" string[] diskArray = getValueInQuotes(dm["Antecedent"].ToString()).Split(','); string driveNumber = diskArray[0].Remove(0, 6).Trim(); var disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive"); foreach (ManagementObject disk in disks.Get()) { //disk["Name"] 大致为:\\.\PHYSICALDRIVE1 //disk["InterfaceType"] 大致为:USB if (disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) && disk["InterfaceType"].ToString() == "USB") { //disk["PNPDeviceID"] 大致为:USBSTOR\DISK&VEN_TECLAST&PROD_COOLFLASH(S)&REV_1100\AAGP30PMDRVS56NK&0 return parseSerialFromDeviceID(disk["PNPDeviceID"].ToString()); } } } } return null; }
Resharper插件提示我这个可以转变为一个LINQ表达式,我想它会怎么转呢,于是点了一下,就变成了:
//返回结果大致为:AAGP30PMDRVS56NK public string GetUsbDiskSnViaDriveLetter(string strUsbDiskDriveLetter) { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_LogicalDiskToPartition"); return (from ManagementObject dm in searcher.Get() let strDriveLetter = getValueInQuotes(dm["Dependent"].ToString()) where strDriveLetter == strUsbDiskDriveLetter select getValueInQuotes(dm["Antecedent"].ToString()).Split(',') into diskArray select diskArray[0].Remove(0, 6).Trim() into driveNumber let disks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive") from ManagementObject disk in disks.Get() where disk["Name"].ToString() == ("\\\\.\\PHYSICALDRIVE" + driveNumber) && disk["InterfaceType"].ToString() == "USB" select parseSerialFromDeviceID(disk["PNPDeviceID"].ToString())).FirstOrDefault(); }
代码貌似少多了,粗一看还以为这是别的语言,但坦白说可读性真差……长长的一行。
感觉Resharper也实在太智能了。