Remove list item based on property value

3

I have a list of objects, the objects have the following properties

public class oItem {
    public decimal nit_codit { get; set; }
    ... etc
}

Then I have the list of objects

List<oItem> PlItens = new List<oItem>();

Let's suppose that the list was loaded with n records, I want to remove the objects whose nit_codit property is 0 from the list.

I tried:

if (PlItens.Exists(x => x.nit_codit == 0)) {
     PlItens.Remove(x);
}

And also:

PlItens.Remove(x => x.nit_codit == 0);

But by the way it's not like this .. does anyone know how to do it?

    
asked by anonymous 14.10.2014 / 15:15

3 answers

3

Try this:

 PlItens.RemoveAll(x => x.nit_codit == 0);  
    
14.10.2014 / 15:37
2

This first way you tried:

if (PlItens.Exists(x => x.nit_codit == 0)) {
    PlItens.Remove(x);
}

It does not work because "x" does not exist on the line where you have PlItens.Remove(x); , it only belongs to the lambda expression scope within the Exists method.

In this second way you used the Remove method, you would need to pass an oItem object to be removed, so try to use the RemoveAll method as it allows you to filter the elements:

 PlItens.RemoveAll(x => x.nit_codit == 0); 

You can also do this in other ways by using Linq for example:

using System.Collections.Generic;   
using System.Linq;

//Cria a lista
List<oItem> PlItens = new List<oItem>();

//Cria itens para adicionar na lista
oItem item1 = new oItem(){nit_codit = 0};
oItem item2 = new oItem(){nit_codit = 1};

//Adiciona os itens na lista
PlItens.Add(item1);
PlItens.Add(item2);

//Obtem os objetos cujo a propriedade nit_codit seja 0
var itensIgualAzero = from i in PlItens.ToList() where i.nit_codit == 0 select i;

foreach (var i in itensIgualAzero)
{
    PlItens.Remove(i);
}
    
14.10.2014 / 15:54
1

It seems to me that you want to remove a list of objects where x => x.nit_codit == 0 , so you have to use RemoveAll to remove a list of data:

PlItens.RemoveAll(PlItens.Where(x => x.nit_codit == 0));
    
14.10.2014 / 15:40