leora leora - 2 months ago 5
C# Question

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.

Answer

If you're using C# 3.0 or better...

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();
}