filter an array in C#
C#ArraysC# Problem Overview
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.
C# Solutions
Solution 1 - C#
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();
}
Solution 2 - C#
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
.
Solution 3 - C#
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();
Solution 4 - C#
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.
Solution 5 - C#
var available = from c in cars where c.IsAvailable == true select c;
Or
var available = cars.Where(c => c.IsAvailable == true);
Solution 6 - C#
an array is filter array when it meets the following conditions:
- if 9 exists in the list 13 must also exist
- 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.!!