【发布时间】:2014-08-16 17:49:34
【问题描述】:
这是一个单人作业,我对其中的一部分有疑问。这是代码;
namespace Assignment_1
{
public partial class Classifier : System.Web.UI.Page // We are using a web form as stated
{
protected void Page_Load(object sender, EventArgs e) // No variables are initiated for the beginning
{
}
protected void ButtonClassify_Click(object sender, EventArgs e)
{
if (this.TextBox1.Text != "")
{
List<string> numbersText = this.TextBox1.Text.Split(',').ToList<string>();
foreach (var item in numbersText)
{
int num = int.Parse(item);
if (RadioButtonList1.SelectedValue == "Both")
{
if (num % 2 == 0)
{
if (CheckBoxDuplicate.Checked == true)
{
List<int> evenNumbers = new List<int>();
evenNumbers.Add(num);
List<int> distinctEvenNumbers = evenNumbers.Distinct().ToList();
ListBoxEvenNumbers.DataSource = distinctEvenNumbers;
}
else
{
//Put the results into the respective boxes
ListBoxEvenNumbers.Items.Add(num.ToString());
}
}
else
{
//Put the results into the respective boxes
ListBoxOddNumbers.Items.Add(num.ToString());
}
}
if (RadioButtonList1.SelectedValue == "Even")
{
if (num % 2 == 0)
{
//Put the results into the respective boxes
ListBoxEvenNumbers.Items.Add(num.ToString());
}
}
if (RadioButtonList1.SelectedValue == "Odd")
{
if (num % 2 == 1)
{
//Put the results into the respective boxes
ListBoxOddNumbers.Items.Add(num.ToString());
}
}
让我解释一下这个问题以及我做了什么。用户将数字列表插入文本框中,然后有 3 个选项(radiolistbutton)。他可以列出偶数、奇数或两种类型的数字。它们显示在偶数和奇数列表框(2 个列表框)中。我已经完成了这部分。
有一个复选框可以删除重复项,用户可以根据需要检查它。如果选中该按钮,则代码应删除重复项。我尝试在第四个“if-else”“if (CheckBoxDuplicate.Checked == true)”中完成这部分。我理解它的方式,我检查数字是否是偶数,然后检查 CheckboxDuplicate 按钮。如果选中,我将值放在一个新列表中,然后删除重复的值。然后放入 EvenNumbers 列表框。由于某种原因,这部分不起作用。
如果您想帮助我,请不要只发布您的答案。这是我在 C# 中的第一个项目,我还很难理解一个优雅的解决方案。如果你有时间,请检查我的代码,让我知道我哪里出错了。提前感谢您的时间。
【问题讨论】:
-
在您的第二部分中,您只是添加了 1 个数字?你在那里做什么 ?另外,请检查我的答案以获得上述更易读的代码。
-
@Noctis:我为 numbersText 列表中的项目赋予 num 值?第 9 行。我是 C# 新手,我的代码还不优雅。
-
这不是您的完整代码。请更新它。
标签: c# visual-studio-2012