N
N
Nonpacie2020-11-28 20:03:17
C++ / C#
Nonpacie, 2020-11-28 20:03:17

How to remove list item by its type?

There is an abstract class Shape, and three heirs of Square, Circle, Triangle. Created a List in which some figures will be placed. Faced with the fact that you need to write a method to remove elements from the list by their type. The user types for example: Circle and all elements of type Circle are removed from the list. Tried to click something through LINQ, nothing came of it. I ask for hints!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
Grish Poghosyan, 2020-11-28
@Nonpacie

static class Extensions
{
  public static IEnumerable<TSource> Remove<TSource>(this IEnumerable<TSource> collection, Predicate<TSource> predicate)
  {
    foreach(TSource item in collection)
    {
       if(!predicate?.Invoke(item)) yield return item;
    }		
  }
}

class Program
{
    public static void Main()
    {
        IEnumerable<Shape> shapes = new List<Shape> { new Square(), new Triangle(), new Circle(), new Circle() };
        foreach(var shape in shapes.Remove(t => t.GetType() == typeof(Circle)))
        {
           Console.WriteLine(shape.GetType()); // Square, Triangle
        }
    }
}

V
Vasily Bannikov, 2020-11-28
@vabka

list = list.Where(x=>x.GetType() != typeof(Circle)).ToList()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question