这是我的代码,但我不确定在某个区域放置什么(见下文),因为我一直在那里收到错误。我基本上加载一个文本文件,然后删除任何重复的值,然后输出文本文件的更新副本。
文本文件如下,
5
5
3
2
2
3
我的代码是
{
public partial class Form1 : Form
{
//Global Variable
int[] Original;
public Form1()
{
InitializeComponent();
}
//Exit Application
private void mnuExit_Click_1(object sender, EventArgs e)
{
this.Close();
}
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//Code to Load the Numbers From a File
OpenFileDialog fd = new OpenFileDialog();
//Open the File Dialog and Check If A File Was Selected
if (fd.ShowDialog() == DialogResult.OK)
{
//Open File to Read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
//Go Through Text File
for (int i = 0; i < Records; i++)
{
Original[i] = int.Parse(sr.ReadLine());
}
}
}
private void btnOutput_Click(object sender, EventArgs e)
{
//Store Original Array
string Output = "Original \n";
//Output Original Array
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
//Create TempArray
int[] TempArray = new int[Original.Length];
//Set TempArray Equal to Original Array
for (int i = 0; i < Original.Length; i++)
{
TempArray[i] = Original[i];
}
//Current Index
int Counter = 0;
//Loop Through Entire Array
for (int i = 0; i < TempArray.Length; i++)
{
for (int j = i + 1; j < TempArray.Length; j++)
{
//Replace Duplicate Values With '-1'
if (TempArray[i] == TempArray[j])
{
TempArray[j] = -1;
Counter++;
}
}
}
//Set Size of Original Array
Original = new int[Original.Length - Counter];
//Counter = 0;
//Remove -1 Values
//error begins here
for (int i = 0; i < Original.Length; i++)
{
for (int j = i + 1; j < Original.Length; j++)
{
//Set Original Array Equal to TempArray For Values Not Equal To '-1'
if (j != -1)
{
Original[j] = TempArray[j];
//Counter++;
}
}
}
//error ends here
//Final Output -- The New Array
Output = Output + "Original Without Duplicates\n";
for (int i = 0; i < Original.Length; i++)
{
Output = Output + Original[i] + "\n";
}
lblOutput.Text = Output;
}
}
}
答案 0 :(得分:1)
我理解你的逻辑,但是所有懒惰的程序员都是如此。您可以简单地使用LINQ
以防止重复。像你一样加载数组并使用Distinct
方法,如下所示:
int[] newArray = Orginal.Distinct().ToArray();
古德勒克。