有没有办法将字典对的值传递给 C# 中的变量?

我是 C# 的新手。我试图根据 IF 语句的计算结果是否为 True,将字典对的值存储在变量中,但它的行为不像我预期的那样。我正在尝试通过我正在从事的项目获得创意,并想学习如何以这种方式使用字典。


string newFileName = "EOYReportPRF.xls";

string dirInfo_Source = "C:\Temp\"


Dictionary<string, string> fileNameChanges = new Dictionary<string, string>();

fileNameChanges.Add("EOYReportPRF.xls", "EOY_PRF.xls");

fileNameChanges.Add("PayrollEOY.xls", "EOY_SU.xls");

fileNameChanges.Add("PRFFundingStatement.xls", "FS_PRF.xls");

fileNameChanges.Add("SUFundingStatement.xls", "FS_SU.xls");


if (fileNameChanges.ContainsKey(newFileName))

    {

    File.Move(dirInfo_Source + newFileName, dirInfo_Source + fileNameChanges.Values.ToString());

    }

我知道代码不正确。我只是想让它正常工作。我想遍历一个目录,将每个文件的名称传递给 newFileName 变量。如果 newFileName 匹配字典中的键,例如“EOYReportPRF.xls”,那么我想使用字典对的值作为文件名。需要一些帮助来思考这个问题。谢谢!


肥皂起泡泡
浏览 107回答 2
2回答

狐的传说

您需要获取密钥的实际值:&nbsp; &nbsp; &nbsp; &nbsp; string newFileName = "EOYReportPRF.xls";&nbsp; &nbsp; &nbsp; &nbsp; string dirInfo_Source = @"C:\Temp\";&nbsp; &nbsp; &nbsp; &nbsp; Dictionary<string, string> fileNameChanges = new Dictionary<string, string>();&nbsp; &nbsp; &nbsp; &nbsp; fileNameChanges.Add("EOYReportPRF.xls", "EOY_PRF.xls");&nbsp; &nbsp; &nbsp; &nbsp; fileNameChanges.Add("PayrollEOY.xls", "EOY_SU.xls");&nbsp; &nbsp; &nbsp; &nbsp; fileNameChanges.Add("PRFFundingStatement.xls", "FS_PRF.xls");&nbsp; &nbsp; &nbsp; &nbsp; fileNameChanges.Add("SUFundingStatement.xls", "FS_SU.xls");&nbsp; &nbsp; &nbsp; &nbsp; if (fileNameChanges.ContainsKey(newFileName))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var filename = fileNameChanges[newFileName];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File.Move(dirInfo_Source + newFileName, dirInfo_Source + filename);&nbsp; &nbsp; &nbsp; &nbsp; }那应该行得通。

守着一只汪

您可以尝试使用 TryGetValue 方法。&nbsp;string val;&nbsp;string [] fileEntries = Directory.GetFiles(dirInfo_Source);&nbsp; &nbsp; foreach(string fileName in fileEntries){&nbsp; &nbsp; &nbsp; &nbsp; if(fileNameChanges.TryGetValue(fileName, out val)){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;File.Move(dirInfo_Source + fileName , dirInfo_Source + val);&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;}&nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP