Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...