c# - 从循环中创建唯一字符串列表的最快方法?

标签 c# .net optimization

我有一组字符串(~80 000)我只能通过 hits.Doc(int).Get("fieldName") 方法顺序访问。

List<string> idStrings = new List<string>();
int count = hits.Length();
for (int i = 0; i < count; i++)
{
    string idString = hits.Doc(i).Get("id");
    if (!idStrings.Contains(idString))
        idStrings.Add(idString);
}

稍后必须对字符串进行 int.TryParse() 处理。 我认为应该有一种更快的方法来做到这一点。有什么建议吗?

最佳答案

首先,使用一个Hashset<string>代替列表,Contains 方法会更快:

int count = hits.Length();
Hashset<string> idStrings = new Hashset<string>();

编辑:如果您使用哈希集,则不必调用“包含”,因为它不能包含重复项。只需使用添加,它会自动删除重复值。

关于c# - 从循环中创建唯一字符串列表的最快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/681049/

相关文章:

c# - 如何将 CurrentCulture 格式的日期时间转换为公历日期时间?

C# 处理 IDisposable

javascript - C# MVC JsonResult 动态数据表

android - 拥有多个密度的android有什么意义

c# - 如何获取执行上下文菜单的控件名称

c# - asp.net mvc 3 模型绑定(bind)下拉列表

c# - 测试 WCF Web 服务

c# - 使用 yield 或改变算法优化代码

optimization - 为什么INC和ADD 1有不同的表现?

asp.net - asp 服务器错误 ' Could not load file or assembly ' 但程序集肯定存在。