订购字典

the*_*Guy 2 c# sorting dictionary duplicates

我正在使用此代码向字典添加信息:

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

// I believe this is what needs to change..?
var ordered = from k in dictionary.Keys select k;
Run Code Online (Sandbox Code Playgroud)

当我用StreamWriter它打印出来的时候,按照它添加到的顺序将它打印出来dictionary.

我想要做的是按顺序打印出来,首先比较PartDescription然后将PartNumber数字打印出来.

文件看起来像这样:

PartDescription        PartNumber        Name        X        Y        Rotation
1608RTANT              147430            J1        20.555   -12.121       180
TANTD                  148966            J2        20.555   -12.121       270
SOMETHING              148966            R111      20.555   -12.121       360
SOMETHING              148966            C121      20.555   -12.121       180
SOMETHING              148966            R50       205.555  -12.121       180
SOMETHING              148966            R51      -205.555  125.121       270
SOMETHING              148966            R52       20.555   -12.121       0
SOMETHING              148966            C12       20.555   -12.121       0
1709RTANT              147430            C98       20.555   -12.121       0
1608RTANT              147429            QD1       20.555   -12.121       180
1709RTANT              147430            F12       20.555   -12.121       0
1609RTANT              147445            P9        20.555   -12.121       180
Run Code Online (Sandbox Code Playgroud)

StreamWriter会输出这样的:

1, 1608RTANT, 147429, 1   //Line#, PartDescription, PartNumber, # of Duplicates (from dictionary key)
2, 1608RTANT, 147430, 1
3, 1609RTANT, 147445, 1
4, 1709RTANT, 147430, 2
5, SOMETHING, 148966, 6
6, TANTD, 148966, 1
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

那么你肯定可以轻松地按顺序获得密钥:

var ordered = from k in dictionary.Keys orderby k select k;
Run Code Online (Sandbox Code Playgroud)

甚至更简单:

var ordered = dictionary.Keys.OrderBy(x => x);
Run Code Online (Sandbox Code Playgroud)

请注意,您不应该依赖于按照添加顺序存储对的字典 - 基本上您不应该假设字典中的任何排序.