Delete line from a list in C#

Asked

Viewed 3,060 times

3

I have a list as described below I would like to delete a line from the list mylistnova1 as condition is true. I try to do as described below but it generates error! Could you please help me? Abs. public Datatable Treatquery(Datatable table ) {

        NewDb openDb3 = new NewDb();
        DataTable Carga01 = tabela.Copy();
        DataTable Carga02 = tabela.Copy();
        //Carrega  DataTablepara uma lista
        var mylist = tabela.AsEnumerable().ToList();
         var mylistnova = tabela.AsEnumerable().ToList();
          var mylistnova1 = tabela.AsEnumerable().ToList();

    //    var mylist1 = ResultadoNovo.AsEnumerable().ToList();
        var mylist3 = Carga02.AsEnumerable().ToList();

           using (MySqlConnection db = openDb3.AbrirConexaoMySql())
                {
                    try
                    {
                        db.Open();



        foreach (var Item in mylist3)
        {

            string renavamrecebe = Convert.ToString(Item.ItemArray[1]);
        }


        foreach (var item02 in mylist)
         {

         string renavanRecebido = item02.ItemArray[01].ToString();
         string ComparaceuNoCartorio = item02.ItemArray[20].ToString();
         Datarecebe = item02.ItemArray[20].ToString();
                 foreach (var item03 in mylistnova1)
                 {
                      string tipocomptaVendaRecebe = Convert.ToString(item03.ItemArray[20]);
                Datarecebe1 = Convert.ToString(item03.ItemArray[15]);

                        renavamContagem = Convert.ToInt32((MamData.MySql.DUT.SelectQuantidadeRenavan(db, renavanRecebido, Datarecebe1)));




                        if (renavamContagem > 1)
                        {

                            if (renavanRecebido == Convert.ToString(item03.ItemArray[1]) && tipocomptaVendaRecebe == "C")
                            {

                                // Marco as linhas a serem deletadas
                                mylistnova1.RemoveAll(x => x == item03.ItemArray[1]); 

                            }


                        }




                 }
         }
        }



                    catch
                    {

                    }
                    db.Close();
                }
           DataTable ResultadoNovo = mylistnova1.CopyToDataTable<DataRow>();
           return (ResultadoNovo);
    }


    public DataTable ConvertToDataTable<T>(IList<T> data)
    {
        PropertyDescriptorCollection properties =
           TypeDescriptor.GetProperties(typeof(T));
        DataTable table = new DataTable();
        foreach (PropertyDescriptor prop in properties)
            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
        foreach (T item in data)
        {
            DataRow row = table.NewRow();
            foreach (PropertyDescriptor prop in properties)
                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
            table.Rows.Add(row);
        }
        return table;

    }

}

}

  • Which error is generating and on which line?

  • In fact it does not give any error but in compensation, do not delete the line from the list if it is true...

  • tries to modify the line mylistnova1.RemoveAll(item04 => item04 == item04.ItemArray[1]); for mylistnova1.RemoveAll(x => x == item04.ItemArray[1]); and see if it works

  • Puts the declaration of the two lists and if they are objects puts the objects in the question. It is not difficult to exclude no, puts the statements that makes it easier to see the problem

  • I updated Carlos the code for full

2 answers

6


From what I understand you want to do a validation on the list item mylistnova1 and if validated then you delete it from the list.

In this case you cannot delete from a list that is in the loop, for example:

(THIS OF ERROR)

foreach (var item in lista)
{
    lista.Remove(item);
}

{"Collection has been modified; maybe the enumeration operation is not executed."}

In that case you can use the .ToList() for it to make a memory copy of the list and run the copy, releasing the original list to be able to delete.

Here he erases the lista all:

foreach (var item in lista.ToList())
{
     lista.Remove(item);
}

In your case I would do so:

foreach (var item03 in mylistnova1.ToList())
                 {
                      string tipocomptaVendaRecebe = Convert.ToString(item03.ItemArray[20]);
                Datarecebe1 = Convert.ToString(item03.ItemArray[15]);

                        renavamContagem = Convert.ToInt32((MamData.MySql.DUT.SelectQuantidadeRenavan(db, renavanRecebido, Datarecebe1)));




                        if (renavamContagem > 1)
                        {

                            if (renavanRecebido == Convert.ToString(item03.ItemArray[1]) && tipocomptaVendaRecebe == "C")
                            {

                                // Marco as linhas a serem deletadas
                                mylistnova1.Remove(item03); 

                            }


                        }




                 }

UPDATING

As you spoke of slowness in consultation so I believe you are dealing with a lot of data, check whether the .ToList() will maintain the desired performance.

  • Perfect Ricardo!!! It was right!!! Thank you very much.... How can I validate you yourself?

  • There’s a "V" below where you vote up or down on the left side of the beginning of the answer. Click on this V. I’m glad it worked.

2

Try it this way:

mylistnova1.Remove(mylistnova1.Single(item04 => item04.propriedade == comparador)); 
  • Did not cause any effect ...that is, did not give error and also did not delete the line... A question... Andre, the variable Item4 what would be? because in foreach is item03 !!! There is deletion of line in list or I will have to convert to a Datatable?

  • Joelias, don’t you know what a variable in your code is? You even put it in the question.

  • I gave a full update on the code

  • The item04 is an iterator that exists having the structure of the LINQ query. This variable will transmute into each item on the list during the search, until the condition is found. I updated the answer, because there was a syntax error. I also changed the name of the variables to make it easier to understand. No need to convert to datatable, lists are mutable by nature =)

  • I’m sorry the redundant fields but it’s just that I was testing with Datatables and it even worked but the query got too slow.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.