This code snippet shows how to remove a specified element from an array in C# using multiple ways i.e., using Array.FindAll
method, Using Enumerable.Where
Method.
Using Array.FindAll Method:
using System;
using System.Linq;
public class RemoveElement
{
public static void Main()
{
// Array
int[] array = { 100, 200, 300, 400, 500, 600 };
// Item to be removed from an array
int itemToRemove = 300;
// Find and remove a specified item/element from an arry
array = Array.FindAll(array, i => i != itemToRemove).ToArray();
// Iterate an array and print
foreach(var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
Output:
100
200
400
500
600
Using Enumerable.Where Method:
using System;
using System.Linq;
public class RemoveElement
{
public static void Main()
{
// Array
int[] array = { 100, 200, 300, 400, 500, 600 };
// Item to be removed from an array
int itemToRemove = 300;
// Find and remove a specified item/element from an arry using "Where"
array = array.Where(i => i != itemToRemove).ToArray();
// Iterate an array and print
foreach(var item in array)
{
Console.WriteLine(item);
}
Console.ReadKey();
}
}
Output:
100
200
400
500
600
Comments (0)