Remove list item based on property value

Asked

Viewed 2,450 times

3

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

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

So I have the list of objects

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

Suppose the list was loaded with n records, I want to remove from the list, objects whose nit_codit property is 0..

I tried to:

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

And also:

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

But apparently it’s not like that. Somebody knows how to do it.?

  • You’re trying to remove a list of data and not just data, right?

  • You were almost @William the second way was to just complete the remove.

  • Thanks to all the answers, it worked with the solution of @Diegosantos, again, thank you all.

3 answers

3


Try it like this:

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

2

That first way you tried:

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

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

This second way that you used the Remove method, you would need to pass an object to be removed, so try using the Remove method Removeall because it allows filtering the elements:

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

You can also do it 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);
}

1

As far as I’m concerned, you want to remove a list of objects where x => x.nit_codit == 0, then you have to use the RemoveAll to remove a data list:

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

Browser other questions tagged

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