Ordering a Dictionary
I am adding information to a dictionary using this code:
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;
When I use the StreamWriter
to print out the lines it is printing it out in the order it was added to the dictionary
.
What I am trying to do is print it out in an order that first compares the PartDescription
and then the PartNumber
and prints it out numerically.
the File looks like this:
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
The StreamWriter
would output like this:
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
Well you could certainly get the keys in an ordered way easily:
var ordered = from k in dictionary.Keys orderby k select k;
Or even more simply:
var ordered = dictionary.Keys.OrderBy(x => x);
Note that you shouldn't rely on the dictionary storing the pairs in the order in which you added them - basically you shouldn't assume any ordering out of the dictionary.
精彩评论