Answer the question
In order to leave comments, you need to log in
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
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
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question