Search code examples
c#listooplinked-listbinaryfiles

Errors in List deleting


I have created a list and a binary file to store data. Now I try to remove from list but it's not working, why?

Errors showing :

Error 2 : Argument 1: cannot convert from 'XYZ_System.Log' to 'System.Predicate' E:\Degree Assignment\Application development-semester 1\XYZ_System\XYZ_System\RegisterUser.cs 239 32 XYZ_System

Error1 :The best overloaded method match for 'System.Collections.Generic.List.RemoveAll(System.Predicate)' has some invalid arguments E:\Degree Assignment\Application development-semester 1\XYZ_System\XYZ_System\RegisterUser.cs 239 17 XYZ_System

    private void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            Log lg = new Log();
           // lg.Username = this.textBox1.Text;
            //lg.Password = this.textBox2.Text;
           // lg.Name = this.txtname.Text;
           // lg.Contact = Convert.ToInt32(this.txtContact_no.Text); ;
           // lg.Email = this.txtEmail_Address.Text;

            Stream stream = File.Open("Login.bin", FileMode.Open);
            BinaryFormatter bformatter = new BinaryFormatter();
            list = (List<Log>)bformatter.Deserialize(stream);
            stream.Close();

            list.RemoveAll(lg);

           // dtvregister.DataSource = list;

            {
                MessageBox.Show("Selected details has been deleted !", "Success");
                Reset();
            }

        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Solution

  • list.RemoveAll() required a function (Predicate<T>) that returns a boolean that will be called per item, if the item should be removed. This is a definite example:

    private bool ValidateItem(Log lg)
    {
        if(lg.Name == "John")
            return true;
        else
            return false;
    }
    
    list.RemoveAll(ValidateItem);
    

    But with lambda expressions, this does the same: list.RemoveAll(lg => lg.Name == "John");

    In your situation this can be used: list.RemoveAll(lg => true);, but you'd better use list.Clear(); instead.