我是 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”,那么我想使用字典对的值作为文件名。需要一些帮助来思考这个问题。谢谢!
最佳答案
您需要获取键的实际值:
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))
{
var filename = fileNameChanges[newFileName];
File.Move(dirInfo_Source + newFileName, dirInfo_Source + filename);
}
这应该有效。
关于c# - 有没有办法将字典对的值传递给 C# 中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190594/