0

I am reading numbers from file, but how can I make the program reading the numbers and saving in the array only the numbers that are not listed in the file several times and will give me the number of all the unique numbers in the file so I can use it later in the code?

private void button2_Click(object sender, EventArgs e)
{
    System.IO.Stream myStream;
    this.openFileDialog1.Filter = "TXT files|*.txt";
    this.openFileDialog1.InitialDirectory = @"C:\";
    if (this.openFileDialog1.ShowDialog() == DialogResult.OK) {

        //CHECKING FOR EXCEPTIONS
        try {
            if ((myStream = this.openFileDialog1.OpenFile()) != null) {
                System.IO.StreamReader myRead = new System.IO.StreamReader(myStream);
                this.textBox2fayl.Text = myRead.ReadToEnd();
                ia = this.textBox2fayl.Text.Split(' ').Select(int.Parse).ToArray();

                //SHOW THE LENGHT OF THE ARRAY
                //string s="";
                // int size = ia.Length;
                // foreach (int x in ia)
                // s += x + "-";
                // MessageBox.Show("Length="+size+","+s);
                myRead.Close();
                myStream.Close();
            }
        } catch (FormatException xx) {
            MessageBox.Show("Файлът трябва да съдържа САМО цели числа, разделени с интервал! (" + xx.Message + ")");
            ia = null;
        } catch (Exception ex) {
            MessageBox.Show("Файлът не може да бъде отворен.Грешка:" + ex.Message);


        }
    }
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
Daniela Gocheva
  • 63
  • 2
  • 11
  • 4
    Possible duplicate of [How do I remove duplicates from a C# array?](https://stackoverflow.com/questions/9673/how-do-i-remove-duplicates-from-a-c-sharp-array), then take the `Length` of the array to get the... length of the array. – Heretic Monkey Mar 13 '18 at 18:56
  • You should use a [`HashSet`](https://msdn.microsoft.com/en-us/library/bb359438(v=vs.110).aspx), not an array. – Dour High Arch Mar 13 '18 at 18:57

1 Answers1

0

Can you just use Distinct() after the Select()? That will give you unique values.

ia = this.textBox2fayl.Text.Split(' ').Select(int.Parse).Distinct().ToArray();
Keith Aymar
  • 876
  • 7
  • 10