我的代码遇到问题,向您解释了我希望获得的信息:
我的词典代码:
class RacesMask
{
Dictionary<string, string> rMask = new Dictionary<string, string>();
public RacesMask()
{
rMask.Add("Toutes", "-1");
rMask.Add("Humains", "1");
rMask.Add("Orcs", "2");
rMask.Add("Nains", "3");
rMask.Add("Elfes de la nuit", "4");
rMask.Add("Mort-vivants", "5");
rMask.Add("Taurens", "6");
rMask.Add("Gnomes", "7");
rMask.Add("Trolls", "8");
rMask.Add("Gobelins", "9");
rMask.Add("Elfes de Sang", "10");
rMask.Add("Draeneis", "11");
rMask.Add("Worgens", "22");
rMask.Add("Pandarens", "24");
rMask.Add("Sacrenuit", "27");
rMask.Add("Tauren de Haut-Roc", "28");
rMask.Add("Elfe du vide", "29");
rMask.Add("Draeneï sancteforge", "30");
}
public Dictionary<string, string> GetRacesMask() { return rMask; }
}
选择:人类(我的词典中为1)和兽人(我的词典中为2)
和一个消息框显示结果2 +1 = 3
我的列表框的代码:
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
RacesMask raceMask = new RacesMask();
Dictionary<string, string> rM = raceMask.GetRacesMask();
foreach (var rMask in listBox1.SelectedItems)
{
var selection1 = int.Parse(rM[rMask.ToString()]);
var selection2 = int.Parse(rM[rMask.ToString()]);
var total = selection1 + selection2;
MessageBox.Show(total.ToString());
}
预先感谢您的帮助
答案 0 :(得分:1)
您可以在循环外使用变量total
,然后对total
变量列表框中的每个选定项的值求和,如下所示:
int total = 0;
foreach (var rMask in listBox1.SelectedItems)
{
selection = int.Parse(rM[rMask.ToString()]);
total = total + selection;
}
MessageBox.Show(total.ToString()); // now show the result finally.
答案 1 :(得分:1)
您将在循环的每次迭代中重置total
。要么在循环外声明total
变量,然后在每次迭代中添加到变量中,要么可以使用LINQ:
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
var raceMask = new RacesMask();
var rM = raceMask.GetRacesMask();
var total = (from s in listBox1.SelectedItems
select int.Parse(rM[s.ToString()]).Sum();
MessageBox.Show(total);
}
答案 2 :(得分:0)
您的逻辑有缺陷。它只会返回单个选择的值。试试这个:
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
RacesMask raceMask = new RacesMask();
Dictionary<string, string> rM = raceMask.GetRacesMask();
int total = 0;
foreach (var rMask in listBox1.SelectedItems)
{
total += int.Parse(rM[rMask.ToString()]);
}
MessageBox.Show(total.ToString());