-2

using linq I want to check certain condition, if that condition is met I want to remove that object from the list

pseudo code

if any object inside cars list has Manufacturer.CarFormat != null
delete that object

if (muObj.Cars.Any(x => x.Manufacturer.CarFormat != null))
{
    ?
}
user1765862
  • 13,635
  • 28
  • 115
  • 220

2 Answers2

4

using the List function RemoveAll, you can

muObj.Cars.RemoveAll(x => x.Manufacturer.CarFormat != null);
Slepz
  • 460
  • 3
  • 18
1

I don't have this RemoveAll method on IList

That's because RemoveAll is a method on List<T>, not IList<T>. If you don't want to try casting to List<T> (what if it fails?) then one option is loop through by index (in reverse order so as to not mess up the index counting:

for (int i = muObj.Cars.Count - 1; i >= 0; i--)
{
    if(muObj.Cars[i].Manufacturer.CarFormat != null)
        muObj.Cars.RemoveAt(i);
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240