c# - 字典排序

标签 c# list dictionary streamwriter

我正在使用 var ordered = dictionary.Keys.OrderBy(x => x); 来订购字典。

按字母数字顺序排列字典非常有效,我想保持这种方式并添加一些异常(exception)...

所以现在,有序字典的输出如下所示:

1: "0603C" "113456" 1
2: "0603C" "984132" 8
3: "0603R" "11115" 3
4: "0603R" "13554" 1
5: "1608C_1.0" "119764" 2
6: "1608C_1.0" "147429" 54
7: "1608R_1.0" "122951" 4
8: "1608R_1.0" "147446" 1
9: "1608R_1.0" "147448" 23
10: "3216" "110762" 2
11: "TANT23" "119764" 2
//more here...

..但我希望它看起来像这样:

1: "0603R" "11115" 3
2: "0603R" "13554" 1
3: "0603C" "113456" 1
4: "0603C" "984132" 8
5: "1608R_1.0" "122951" 4    //**NOTICE**: The "R" and "C" endings after 1608 and 0603
6: "1608R_1.0" "147446" 1    // were switched. I would like to switch all "C" and "R"
7: "1608R_1.0" "147448" 23   // endings if they are the same value before.
8: "1608C_1.0" "119764" 2
9: "1608C_1.0" "147429" 54
10: "3216" "110762" 2
11: "TANT23" "119764" 2
//more here...

到目前为止,这是我的代码的样子:

StreamWriter sw = new StreamWriter(saveFile.FileName);
Dictionary<string, int> dictionary = new Dictionary<string, int>();
List<string> lineList = new List<string>();
int j = 1;
lineList = theFuji1List.Select(line =>
{
    int nameLength = line.Name.Length;

    if (line.PartDescription != "")
        return line.PartDescription + " " line.PartNumber + " " + line.TWidth + " " + line.Name.Remove(1, nameLength - 1) + "\n";

    else
        return "N/A " + line.PartNumber + " " + line.TWidth + " " + line.Name.Remove(1, nameLength - 1) + "\n";
})
    .Where(x => !(x.Contains("FID") || x.Contains("EXCLUDE")))
    .ToLisT();

foreach (string word in lineList)
{
    if (dictionary.ContainsKey(word))
        dictionary[word]++;
    else
        dictionary[word] = 1;
}

var ordered = dictionary.Keys.Orderby(x => x);   //This is what I think I need to change?

foreach (string key in ordered)
{
    string[] splitKey = key.Split(' ');

    sw.WriteLine(string.Format("{0}: \"{1}\" \"{2}\" {3}", j, splitKey[0], splitKey[1], dictionary[key]));
    j++;
}

最佳答案

只需将排序表达式的“R”修改为“B”,使其位于“C”之前:

var ordered = dictionary.Keys.Orderby(x => Regex.Replace(x, @"^(\d+)R", "$1B"));

这不会修改您的键 - 它只会影响排序。

关于c# - 字典排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7287440/

相关文章:

c# - AutoMapper 需要 Get Accessor 来设置。 CS0154 属性或索引器 'Id' 无法在此上下文中使用,因为它缺少 get 访问器

python - 对两个值的元组列表进行分组,并返回所有第三个值的列表

list - 在 Kotlin 中,如何在迭代时修改列表的内容

c# - 网上抓取用户认证的网站

c# - Web配置管理器

C# 在以表类型为参数的 SQL Server 中调用用户定义标量函数

json - 如何从 python 中的文件读取 JSON 文件列表?

c# - 使用 operator[] 即时创建字典项

c++11 - c++11 operator[] 相当于 map 插入时的 emplace 吗?

python - 在字典中过滤日期 - python