Как предотвратить дублирование записей в списке

#c# #winforms

#c# #winforms

Вопрос:

Я должен создать программу, которая считывает данные из выходного файла, а также добавить ДОПОЛНИТЕЛЬНЫЙ текст в этот выходной файл с помощью метода «AppendText», чтобы ничего в текстовом файле не было переопределено. Вы можете добавлять элементы в список с помощью текстового поля, но я пытаюсь предотвратить дублирование записей. Я внедрил код, который предположительно предотвращает множественные записи, но он не работает должным образом. Он выдает сообщение о том, что я установил «Дублирующую запись», но он все равно добавляет запись. ЕСТЬ ЛИ СПОСОБ ЭТО ИСПРАВИТЬ? Пожалуйста, помогите, СПАСИБО.

Это код

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;


namespace BIT_UNITS
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();
    }

    private void displayButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Variables
            string unitsList;

            //declare streamReader variable
            StreamReader inputFile;

            //Open file amp; get units list
            inputFile = File.OpenText("BITS_Units.txt");

            //Clear anything currently in the listbox
            unitsListBox.Items.Clear();

            //Read the file's Contents
            while (!inputFile.EndOfStream)
            {
                //Get Units List
                unitsList = inputFile.ReadLine();

                //Display the units list in the listbox
                unitsListBox.Items.Add(unitsList);
            }
            //close the file
            inputFile.Close();

        }
        catch 
        {
            MessageBox.Show("Error");
        }
    }

    private void addUnitButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Declare streamwriter variable
            StreamWriter outputFile;


            //Open file and get a streamwriter object
            outputFile = File.AppendText("BITS_Units.txt");

            //Record inputs to the file
            outputFile.WriteLine(addUnitsTextBox.Text);

            //Close the file 
            outputFile.Close();

            //Determine wether textbox is filled
            if (addUnitsTextBox.Text== Text)
            {
            //Display message
            MessageBox.Show("Unit was successfully added.");
            }

            //Determine wether textbox is filled                
            if (addUnitsTextBox.Text == "")
            {
                MessageBox.Show("Please enter a unit name to add to the list.");

            }

            if (unitsListBox.Items.Contains(addUnitsTextBox.Text))
            {

                MessageBox.Show("This unit already exists");
            }

            else 
            {
                unitsListBox.Items.Add(addUnitsTextBox.Text);
                addUnitsTextBox.Text = "";

            }

          }
        catch (Exception)
        {
            MessageBox.Show("error");
        }
    }

    private void clearButton_Click(object sender, EventArgs e)
    {
        try
        {
            //Clear data
            addUnitsTextBox.Text = "";
            unitsListBox.Items.Clear();
        }
        catch (Exception)
        {
            MessageBox.Show("Error");
        }
    }

    private void exitButton_Click(object sender, EventArgs e)
    {
        //Close the form
        this.Close();
    }
}
}
 

Комментарии:

1. добавляет запись, где? В список или в файл? Вы не проверяете запись на дублирование перед записью ее в файл

2. запись добавляется в файл. итак, как мне проверить его на дублирование.

3. вы можете прочитать файл перед добавлением содержимого и проверить наличие дубликатов записей или иметь локальную переменную, в которой вы храните содержимое файлов (и привязываете свой список), и при добавлении к нему вы проверяете проверку на наличие дубликатов..

Ответ №1:

Перед добавлением элемента в список проверьте, не существует ли он в списке.

      if (!unitsListBox.Items.Contains(unitsList) )
     {
          unitsListBox.Items.Add(unitsList);
     }