filter an array in C#
i have an array of objects (Car[] for example) and there is an IsAvailable Property on the object
i want to use the full array (where IsAvailable is true for some items and false for some others) as the input and return a new array which includes only the items that have IsAvailable = true.
If you're using C# 3.0 or better...
using System.Linq;
public Car[] Filter(Car[] input)
{
return input.Where(c => c.IsAvailable).ToArray();
}
And if you don't have access to LINQ (you're using an older version of .NET)...
public Car[] Filter(Car[] input)
{
List<Car> availableCars = new List<Car>();
foreach(Car c in input)
{
if(c.IsAvailable)
availableCars.Add(c);
}
return availableCars.ToArray();
}
Surprisingly, this question lacks the most natural and efficient answer: Array.FindAll
Car[] availableCars = Array.FindAll(cars, c => c.IsAvailable);
if it was a List<Car>
there is also a List.FindAll
.
Easiest way:
Car[] cars = //...
Car[] filtered = cars.Where(c => c.IsAvailable).ToArray();
Possibly More Efficient:
Car [] cars = //...
List<Car> filteredList = new List<Car>();
for(int i = 0; i < cars.Length; i++)
{
if(cars[i].IsAvailable)
filteredList.Add(cars[i]);
}
Car[] filtered = filteredList.ToArray();