Remove list item based on property value

Posted on

Question :

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)) {

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?


Answer :

Try this:

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


This first way you tried:

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

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

//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)


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));


Leave a Reply

Your email address will not be published. Required fields are marked *