我只想问一下解决二维数组(2列)的最佳方法,它将存储:CandidateName及其各自的VoteCount。
我想要做的是接受来自用户的输入说:投票约翰福音10章,其中约翰是候选人的名字,10是他想给他的投票。所以我需要将{John,10}存储到我的数组中。然而,在此之后我的程序将再次询问用户投票,所以如果我进入VOTE Doe 15,则条目{Doe,15}将被添加到阵列中。如果用户输入VOTE John 2,我的数组需要更新,因此新值为{John,12}。
目前我使用两个arraylists:CandidateName和VoteCount,我只依靠他们的索引进行配对。但是,这不是真的可靠,所以我试图找到另一种方法来解决这个问题。但是,我并不是多维数组的忠实粉丝。
有人可以指出我如何实现这一目标的好方法吗?
答案 0 :(得分:5)
public class VoteManager
{
public Dictionary<string, int> Votes { get; private set; }
public VoteManager
{
Votes = new Dctionary<string, int>();
}
public void AddVotes(string name, int voteCount)
{
int oldCount;
if (!Votes.TryGetValue(name, out oldCount))
oldCount = 0;
Votes[name] = oldCount + voteCount;
}
答案 1 :(得分:3)
您应该使用Associative Array。对于C#,这样的集合是Dictionary
。
var votes = new Dictionary<string, int>();
votes["John"] = 10;
votes["Bob"] = 20;
votes["John"] = 15; // replaces earlier setting
如果您想加入现有投票,则需要检查是否存在现有值:
private Dictionary<string, int> votesByPeep; // initialized in constructor
private void AddVotes(string peep, int votes)
{
if (this.votesByPeep.ContainsKey(peep)
{
this.votesByPeep[peep] += votes;
}
else
{
this.votesByPeep[peep] = votes;
}
}
答案 2 :(得分:1)
为什么不定义具有两个属性Name和VoteCount的结构/类。那你只需要一个数组。
编辑:
我建议这样做,因为您可能需要向候选人添加其他操作或属性。如果您只需要这两个值之间的关联,那么字典就是正确的解决方案。
答案 3 :(得分:1)
这听起来像是一个更好的解决方案是使用Dictionary<TKey, TValue>
。字典/散列表非常适合您将值(投票计数)与给定密钥(用户名)配对的场景。它使更新和查找方案非常容易
class Container {
private Dictionary<string, int> m_voteMap = new Dictionary<string, int>();
public void SetVote(string user, int votes) {
m_voteMap[user] = votes;
}
public int GetVotes(string user) {
int votes;
if (!m_voteMap.TryGetValue(user, out votes)) {
votes = 0;
}
return votes;
}
}
答案 4 :(得分:1)
你可以使用从字符串(名称)到int(投票)的字典,这将为你提供{name,votes}对和一个很好的快速查找
答案 5 :(得分:0)
创建一个名为CandidateVotes
的类,并将其存储在List<CandidateVotes>
集合中。
public class CandidateVotes
{
public string Name {get; set;}
public int Votes {get; set;}
}
答案 6 :(得分:0)
Dictionary<string, int> is your friend
答案 7 :(得分:0)
这听起来像Dictionary<T,U>
的好候选人。在这种情况下,Dictionary<string,int>
,其中键是候选者,值是投票计数。
// Create dictionary as:
Dictionary<string, int> votes = new Dictionary<string, int>();
然后你可以做一些如下的例程:
void AddVotes(string candidate, int numberOfVotes)
{
if (this.votes.Contains(candidate))
{
// Update the "10 to 12" in your scenario
int current = this.votes[candidate];
current += numberOfVotes;
this.votes[candidate] = current;
}
else
this.votes[candidate] = numberOfVotes; // First time a candidate is used...
}
如果您想列出每个候选人的投票数,您可以执行以下操作:
foreach(var pair in this.votes)
{
Console.WriteLine("Candidate {0} has {1} votes.", pair.Key, pair.Value);
}