优化c#代码

时间:2018-01-05 20:56:16

标签: c#-4.0

我有以下代码:

using System;
using System.Linq;
using System.Collections.Generic;

class MainClass
{
    public static void Main(string[] args)
    {
        var maxLetter = 4;
        List<string> wordList = new List<string>();
        Dictionary<int, string> dic = new Dictionary<int, string>(); 
        string word = "Demo Deer Deep Deck Cere Reep Creep Creeps";
        string[] split = word.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

        for (int i = 0; i < split.Length; i++)
        {
            for (int j = 1; j < split.Length - 1; j++)
            {
                var common = split[i].Intersect(split[j]);
                var unCommon = split[i].Except(split[j]).Union(split[j].Except(split[i]));
                var count = common.Count() + unCommon.Count();
                if (count == maxLetter && split[i] != split[j])
                {
                    if (!wordList.Any(l => l == split[i]))
                    {
                        wordList.Add(split[i]);
                    }
                    wordList.Add(split[j]);
                }                
            }
            if (wordList.Count > 0)
            {
                dic.Add(i, String.Join("\n", wordList));
                wordList.Clear();
            }
        }
        Console.WriteLine(String.Join("\n", dic));
        Console.ReadLine();
    }
}

我试图以这样的方式获得结果:

[1, Deer Deep Cere]
[2, Deep Deer Reep]
[4, Cere Deer Creep]
[5, Reep Deep]
[6, Creep Cere]

上面的代码适用于少量字母,但只要我增加字母就可以说500就停止工作了。有没有办法优化它或使其更简单,因此它可以快速工作?

2 个答案:

答案 0 :(得分:0)

您的流程可能需要很长时间。您不应该有在主线程上运行这么长时间的进程。在新的线程或任务中运行代码,它应该运行得很好。

答案 1 :(得分:0)

使用System.Threading.Tasks;

添加

任务任务= Task.Run(()=&gt; {

 Your Code Here

});

控制台。的ReadLine();

确保Console.Readline不在任务范围内,以使控制台保持打开状态。

相关问题