filter an array in C#

Viewed 117125

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.

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

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

A simple solution is to create a new array, loop through the input array and add only those items which satisfy your conditions to the new array, and return the new array:

List<Car> available = new List<Car>();
foreach (Car c in cars) {
    if (c.IsAvailable) {
        available.add(c);
    }
}
//Here you can either just return the list, or create an array from it.
var available = from c in cars where c.IsAvailable == true select c;

Or

var available = cars.Where(c => c.IsAvailable == true);

an array is filter array when it meets the following conditions:

  1. if 9 exists in the list 13 must also exist
  2. if 7 exists in the list then 11 must not exist

solution

int[] a = {7 , 72, 6, 13, 9 };
int i, k = 0, l = 0, m = 0, n = 0;
for (i = 0; i < a.Length; i++)
{
    if (a[i] == 9)
    {
        k = 1;
    }
}
for (i = 0; i < a.Length; i++)
{
    if (a[i] == 13)
    {
        l = 1;
    }
}
for (i = 0; i < a.Length; i++)
{
    if (a[i] == 7)
    {
        m = 1;
    }
}
for (i = 0; i < a.Length; i++)
{
    if (a[i] == 11)
    {
        n= 1;
    }
}
if ((k == 1 && l == 1) && (m == 1 && n == 1))
{
    Console.WriteLine("is not filter array");
}
else if (k == 1 && l!= 1)
{
    Console.WriteLine("is not filter array");
}
else if (m ==1 && n==1)
{
    Console.WriteLine("is not filter array ");
}
else
    Console.WriteLine("is filter array");
Console.WriteLine("the element of an array is:");
for (i = 0; i < a.Length; i++)
{
    Console.WriteLine(a[i]);
}

As i think this code is surely work for if you need to test an array.
reta seboka ambo universtity woliso campuse department of information TECH.!!

Related