gpt4 book ai didi

c# - Decorate-Sort-Undecorate,如何按降序对字母字段进行排序

转载 作者:行者123 更新时间:2023-11-30 17:23:32 25 4
gpt4 key购买 nike

我有大量数据,计算排序键的成本相当高。我想要做的是使用 DSU 模式,我在其中获取行并计算排序键。一个例子:

        Qty   Name      Supplier   
Row 1: 50 Widgets IBM
Row 2: 48 Thingies Dell
Row 3: 99 Googaws IBM

要按数量和供应商排序,我可以使用排序键:0050 IBM0048 Dell0099 IBM。数字右对齐,文本左对齐,根据需要填充所有内容。

如果我需要按降序顺序对数量进行排序,我只需从常量(例如 10000)中减去该值来构建排序键:9950 IBM , 9952 戴尔, 9901 IBM

如何快速/廉价地为 C# 中的字母 字段构建降序键?

[我的数据全部是带有 ISO 8859 扩展字符的 8 位 ASCII。]

注意:在 Perl 中,这可以通过 bit-complementing the strings 来完成:

 $subkey = $string ^ ( "\xFF" x length $string );

将此解决方案直接移植到 C# 中不起作用:

 subkey = encoding.GetString(encoding.GetBytes(stringval).
Select(x => (byte)(x ^ 0xff)).ToArray());

我怀疑是因为在 C#/Perl 中处理字符串的方式不同。也许 Perl 正在按 ASCII 顺序排序,而 C# 正在尝试变聪明?

下面是一段尝试实现此目的的示例代码:

        System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
List<List<string>> sample = new List<List<string>>() {
new List<string>() { "", "apple", "table" },
new List<string>() { "", "apple", "chair" },
new List<string>() { "", "apple", "davenport" },
new List<string>() { "", "orange", "sofa" },
new List<string>() { "", "peach", "bed" },
};
foreach(List<string> line in sample)
{
StringBuilder sb = new StringBuilder();

string key1 = line[1].PadRight(10, ' ');
string key2 = line[2].PadRight(10, ' ');

// Comment the next line to sort desc, desc
key2 = encoding.GetString(encoding.GetBytes(key2).
Select(x => (byte)(x ^ 0xff)).ToArray());

sb.Append(key2);
sb.Append(key1);
line[0] = sb.ToString();
}

List<List<string>> output = sample.OrderBy(p => p[0]).ToList();

return;

最佳答案

可以到达你想要的地方,尽管我承认我不知道是否有更好的整体方式。

直接翻译 Perl 方法的问题是 .NET 根本不允许您对编码如此放任。但是,如果正如您所说,您的数据都是可打印的 ASCII(即由 Unicode 代码点在 32..127 范围内的字符组成)——请注意,没有“8 位 ASCII”这样的东西——那么你可以这样做:

            key2 = encoding.GetString(encoding.GetBytes(key2).
Select(x => (byte)(32+95-(x-32))).ToArray());

在这个表达式中,我已经明确说明了我在做什么:

  • x(我假设它在 32..127 中)
  • 将范围映射到 0..95 以使其从零开始
  • 通过从 95 中减去反转
  • 加 32 映射回可打印范围

它不是很好,但确实有效。

关于c# - Decorate-Sort-Undecorate,如何按降序对字母字段进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2135500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com