首页 > 解决方案 > 将两个字典的值转换为 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);

 }

标签: c#

解决方案


代码行少,语法优雅,希望能满足你的需求

    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);

    }

推荐阅读