字典排序 [英] Dictionary Ordering
本文介绍了字典排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用这个 var ordered = dictionary.Keys.OrderBy(x => x);
来订购一个字典。
I am using this var ordered = dictionary.Keys.OrderBy(x => x);
to order a dictionary.
这样可以很好的排序字典字母数字,我想保持这种方式,并添加了一些例外...
This works great ordering the dictionary alpha-numerically and I would like to keep it this way and add a few exceptions...
所以现在,订单字典如下所示:
So right now, the ordered dictionary looks like this for the output:
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...
..但我希望看起来像这样:
..but I would like it to look like this:
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...
这是我的代码看起来到目前为止:
This is what my code looks like so far:
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之前:
Just modify the "R" to be a "B" for the sort expression, so that it falls before "C":
var ordered = dictionary.Keys.Orderby(x => Regex.Replace(x, @"^(\d+)R", "$1B"));
这不会修改你的密钥 - 它只会影响排序。
This won't modify your keys - it will only affect the sort.
这篇关于字典排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文