CodeGo.net>没有LINQ如何合并两个字典的值?
作者:互联网
我正在创建一个快速民意测验程序.
我被指示使它在没有任何LINQ运算符的情况下工作.
这是我的两本字典:
Dictionary<int, string> ballots = new Dictionary<int, string>();
Dictionary<int, int> votes = new Dictionary<int, int>();
我是这样问选票的:
//Print the ballots as list
Console.WriteLine("Voting Ballots:");
foreach (KeyValuePair<int, string> ballot in ballots)
{
Console.WriteLine("{0} - {1}", ballot.Key, ballot.Value);
}
//Voting process
Console.WriteLine("\nVote for one of the ballots");
Console.WriteLine("---------------------------------");
Console.WriteLine("Write the number of the ballot you want to vote for: ");
int nVote; int.TryParse(Console.ReadLine(), out nVote);
int val;
string nBallot;
//Verify if the ballot exists
if (planillas.TryGetValue(nVote, out nBallot)){
Console.WriteLine("You've voted for the ballot {0}", nBallot);
if (votes.TryGetValue(nVote, out val)) {
votes[nVote] += 1;
}
}else{
Console.WriteLine("The ballot #{0} doesn't exist. \nPlease try again.", nVote);
}
我需要将结果输出如下:
BALLOT ID ——— BALLOT NAME ———— NUMBER OF VOTES
06002
选票ID是一个给定的数字,名字也是如此.
我将结果打印如下:
Console.Clear();
Console.WriteLine("VOTING RESULTS: ");
Console.WriteLine("--------------------------------------------------------------");
Console.WriteLine("BALLOT ID --------- BALLOT NAME ------------ NUMBER OF VOTES");
List<int> nVotes = votes .Keys.ToList<int>();
foreach (KeyValuePair<int, int> ballot in votes )
{
Console.Write("{0} ----- ", ballot.Key);
// I need to print the ballot's name here
Console.Write("----- {0}", ballot.Value);
}
我尝试这样做:
foreach (KeyValuePair<int, int> planilla in votosPlanillas)
{
Console.Write("\n ---------- {0} ---------- ", planilla.Key);
if (planillas.TryGetValue(planilla.Key, out nPlanilla)){
Console.Write("{0} ", nPlanilla);
}
foreach (KeyValuePair<int, string> namePlanilla in planillas) {
Console.Write(" ---------- {0}", planilla.Value);
}
}
但是结果是:
----- BALLOT ID ----- BALLOT NAME ----- NUMBER OF VOTES
---------- 1 ---------- a ---------- 1 ---------- 1 ---------- 1 ---------- 1
---------- 2 ---------- b ---------- 1 ---------- 1 ---------- 1 ---------- 1
---------- 3 ---------- c ---------- 3 ---------- 3 ---------- 3 ---------- 3
---------- 4 ---------- d ---------- 1 ---------- 1 ---------- 1 ---------- 1
在那个结果中,我对第三票投了三票.它正在工作,但是…它正在打印破折号(———-),并且投票数与1号选票相对应.
我怎样才能得到理想的结果?
解决方法:
在开始之前,我建议您更新代码以使Dictionary< int,Ballot>其中Ballot是具有名称和计数的类,因此您无需管理两个字典.而不管…
您当前的问题是另一个foreach循环中的一个foreach循环.如果保证两个字典中的键相同,则可以删除第二个循环:
foreach (KeyValuePair<int, int> planilla in votosPlanillas)
{
Console.Write("\n ---------- {0} ---------- ", planilla.Key);
if (planillas.TryGetValue(planilla.Key, out nPlanilla)){
Console.Write("{0} ", nPlanilla);
}
Console.Write(" ---------- {0}", planilla.Value);
}
请记住,如果您没有使字典正确同步,则if语句将失败,并且您将获得一个带有ID和投票数但没有投票名称的报告条目.
标签:list,dictionary,console-application,c 来源: https://codeday.me/bug/20191024/1922817.html