将600k个字符串加载到HashSet中



我有一个包含大约600k个字符串的列表,我把它们放在一个静态函数中,如下所示:

public static HashSet<string> All()
{
return new HashSet<string>
{
"entry 1", 
"entry 2",
...
"entry 600000"
};
}

启动应用程序需要很长时间,第一次使用HashSet也需要很长的时间。有更好的方法吗?

这是一种可以在应用程序启动时作为后台任务启动的事情,消除了启动延迟的影响。

将其另存为Program.cs文件。它应该运行得很快,对启动时间没有影响。

您需要创建一个utf-8编码的文本文件,每行一个城市,以及您的所有城市。在本例中,我假设它在应用程序根目录中,名为data.txt,但您可以在我的示例代码中更改它。

您可以在应用程序中的任何位置使用MainNamespace.MainClass.CityExists(value)来检查条目是否存在。

显然,这是粗糙但有效的,您可以将其重构为城市服务类或其他什么。。。

using System.Collections.Generic;
using System.Linq;
namespace MainNamespace
{
public static class MainClass
{
private const string cityFilePath = "./data.txt"; // change to your correct path

private static HashSet<string> cities;

// use this method for city lookup checks
public static bool CityExists(string value)
{
while (cities is null)
{
// this is unlikely to trigger, the city data will probably be loaded before your first city query, but just in case...
System.Threading.Thread.Sleep(20);
}
return cities.Contains(value);
}

public static void Main()
{
Task.Run(async () =>
{
// no error handling here, you would likely want to try/catch this and do something appropriate if exception is thrown
HashSet<string> hashSet = (await File.ReadAllLinesAsync(cityFilePath)).ToHashSet(StringComparer.OrdinalIgnoreCase);
cities = hashSet;
}).GetAwaiter();

// go on executing the rest of your application, show main form, etc.
}
}
}

我得到了类似的东西,一个城市列表。

我正在使用一个包含所有值的外部csv文件,并从我的程序中读取它。在我看来要快得多

最新更新