Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter an array in C#

Tags:

arrays

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.

like image 909
leora Avatar asked Dec 16 '09 03:12

leora


People also ask

Can you filter an array?

Using filter() on an Array of Numbers The item argument is a reference to the current element in the array as filter() checks it against the condition . This is useful for accessing properties, in the case of objects. If the current item passes the condition , it gets returned to the new array.

How do you filter items in an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Is filter an array function?

JavaScript Array filter()The filter() method creates a new array filled with elements that pass a test provided by a function. The filter() method does not execute the function for empty elements.

How filter is implemented in C?

The basic steps for applying a FIR filter are the following: Arrange the new samples at the high end of the input sample buffer. Loop through an outer loop that produces each output sample. Loop through an inner loop that multiplies each filter coefficient by an input sample and adds to a running sum.


1 Answers

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(); } 
like image 152
Justin Niessner Avatar answered Sep 18 '22 15:09

Justin Niessner