c# - 将两个字典的值转换为 DateTime
问题描述
foreach
有没有一种方法可以仅使用一个循环(例如)将两个字典的字符串值递归地转换为 DateTime ?
(我在这里先向您的帮助表示感谢)
检查下面的代码:
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Dictionary<string, string> Dict = new Dictionary<string, string>();
Dictionary<string, string> Dict2 = new Dictionary<string, string>();
foreach (var item in Dict)
{
foreach (var item2 in Dict2)
{
if (item.Key == item2.Key)
{
DateTime date1 = DateTime.Parse(item.Value);
DateTime date2 = DateTime.Parse(item2.Value);
var diffInSeconds = (date1 - date2).TotalSeconds;
Console.WriteLine(diffInSeconds);
}
}
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
}
解决方案
代码行少,语法优雅,希望能满足你的需求
static void Main(string[] args)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Dictionary<string, string> Dict = new Dictionary<string, string>();
Dictionary<string, string> Dict2 = new Dictionary<string, string>();
foreach (var item in Dict)
{
if (Dict2.TryGetValue(item.Key, out string date))
{
var diffInSeconds = (DateTime.Parse(item.Value) - DateTime.Parse(date)).TotalSeconds;
Console.WriteLine(diffInSeconds);
}
}
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
}
推荐阅读
- git - GitHub 桌面授权失败
- azure - 如何将 Azure 应用配置与 .Net Framework 4.7.1 MVC 应用一起使用
- python - 在python中合并两个不同长度的列表并计算元素
- javascript - Javascript - 删除地图(对象)的最旧元素
- python - 如何像在管理面板操作中一样仅更新 Django 查询集中的选定记录?
- javascript - DrawerLayoutAndroid 不会打开反应原生
- c++ - C++ 事件系统 - 基于堆的事件触发
- mysql - Discord.py 欢迎消息无法从数据库中获取频道 ID
- python - 为什么 matplotlib savefig 不将轴标签和图形标题保存在与图形相同的白色背景下
- python - 如何在生成的图表中添加测量输入值作为 x 轴标签?