c# - 以自定义顺序获取列表的最快方法

标签 c# performance list sorting

我需要找到以自定义顺序获取一小部分字符串或字符的最快方法。 我发现了很多关于对列表进行排序的问题,但是在董事会或网络上没有关于使用 native 类型对小列表进行排序的问题,我发现的只是更复杂的方式。

对我来说,输入列表是字符串列表还是字符列表并不重要。我的列表有 5 - 7 个项目,它们看起来像这样:“1”、“Q”、“A”、“8”、“9”。我想让我的输入按如下顺序排列:“2”,“3”,“4”,“5”,“6”,“7”,“8”,“9”,“1”,“J”, “Q”、“K”、“A”。

我尝试了以下代码:

1 = 3.1-3.5 毫秒:

static readonly List<String> codeValueSortOrder = new List<String> 
{ 
    "2", "3", "4", "5", "6", "7", "8", "9", "1", "J", "Q", "K", "A" 
};
input.OrderBy(i => codeValueSortOrder.IndexOf(i.ToString())).ToList();

2 = 5.0-6.0 毫秒:

input.OrderBy(i => i[1] == 'A')
     .ThenBy(i => i[1] == 'K')
     .ThenBy(i => i[1] == 'Q')
     .ThenBy(i => i[1] == 'J')
     .ThenBy(i => i.Substring(1, i.Length - 1) == "10")
     .ThenBy(i => i[1] == '9')
     .ThenBy(i => i[1] == '8')
     .ThenBy(i => i[1] == '7')
     .ThenBy(i => i[1] == '6')
     .ThenBy(i => i[1] == '5')
     .ThenBy(i => i[1] == '4')
     .ThenBy(i => i[1] == '3')
     .ThenBy(i => i[1] == '2')
     .ToList();

我还在 codeproject 上查看了一些项目,但这些代码适用于数百万个项目,如果我们只想对 5 到 7 个项目进行排序,我无法想象它们是最有效的方法。我的目标是在 0.1 毫秒内执行排序,我不知道是否可以实现该目标:)

最佳答案

您可以使用Dictionary<string, int>其中键是字符串,值是索引。

您甚至仍然可以使用 List<string>作为基础:

private static readonly List<string> _List = new List<string> { "2", "3", "4", "5", "6", "7", "8", "9", "1", "J", "Q", "K", "A" };
static readonly Dictionary<string, int> Order = _List
    .ToDictionary(str => str, str => _List.IndexOf(str) + 1);

现在您可以使用 List.Sort 当 LINQ 接近时,不需要创建新列表:

var input = new List<string> { "1", "Q", "A", "8", "9" };
int i1, i2;
input.Sort((s1, s2) =>
{
    Order.TryGetValue(s1, out i1);
    Order.TryGetValue(s2, out i2);
    return i1.CompareTo(i2);
});

结果顺序:8,9,1,Q,A

快速测试显示:StopWatch.Elapsed.TotalMilliseconds 0.0045

Dictionary.TryGetValue如果找到字符串则返回索引,否则返回 0。这就是我使用_List.IndexOf(str) + 1的原因上面强制将找到的项目放在最后。

如果你想要降序,你只需颠倒它:

return i2.CompareTo(i1);

关于c# - 以自定义顺序获取列表的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25546097/

相关文章:

c# - WCF 流长度

c# - 在 C# 中获取 Excel 单元格背景颜色的问题

javascript - 每个函数都在单独的 js 文件中,但仅在使用时包含

.net - VS2010 调试/分析时的性能差异

java - 使用列表中的 x 个数字

python - 遍历 2 个列表并构建相对字典的有效方法

c# - C# 中的不可变本地 'variables'

c# - delphi 导入具有指定入口点的dll函数

performance - 每个存储桶的最大沙发床 View 数

python - 关于数组嵌套循环的问题