Nano HE
Nano HE

Reputation: 9297

How to detect one array list include some element in C#

Assume I declared an Array isFind[] like this,

bool[] isFind = new bool[5];

for (int i = 0; i < 5; ++i)
{
   isFind[i] = init(); // initialize isFind[]
}

bool init();
{
  ...; // some code here
}

Is there any quick method (less typing code) to detect there is false element or not in isFind[]? I don't want to for/foreach Loop each element in the array list.

[Update]

.NET 2.0 Used.

quick method (less typing code)

Upvotes: 2

Views: 443

Answers (6)

Gorpik
Gorpik

Reputation: 11028

The only way to find something is to look for it. Assuming that your array is not sorted (if it were, you would only need to look at the first or last element, depending on the sorting), and you have no external cache, you have to check all its elements, so you need a loop. It does not matter if you write it explicitly or through another function, the loop will be there somehow.

Upvotes: 2

Jaroslav Jandek
Jaroslav Jandek

Reputation: 9563

.NET 2.0 version:

bool []isFind = new bool[3];

isFind[0] = true;
isFind[1] = true;
isFind[1] = false;

bool exists = (Array.IndexOf(isFind, false) != -1);

The code uses an internal for loop. Also you had the array declaration wrong.

Upvotes: 2

Regent
Regent

Reputation: 5602

I think you can record whether any element was false during initialization phase:

bool isFind[] = new isFind[5];
bool containsFalse = false;

for (int i = 0; i < isFind.Length; i++)
{
   if (!(isFind[i] = init())) // initialize isFind[]                                 
      containsFalse = true; // and record if item was false
}

Upvotes: 1

apoorv020
apoorv020

Reputation: 5650

This code does not use a seperate loop to find false elements. (There is in general, no way to perform comparison on n objects without looping over all of them at least once.) For a five member array, loop cost is negligible. If you are using bigger arrays, look at BitArray for performance/space benefits.

bool isFind[] = new isFind[5];
bool falseExists = false;

for (int i = 0; i < 5; ++i)
{
   isFind[i] = init(); // initialize isFind[]
   if(!isFind[i])
       falseExists=true;
}

bool init();
{
  ...; // some code here
}

Upvotes: 1

LukeH
LukeH

Reputation: 269318

If you're using .NET2 then you can use the static TrueForAll method:

bool allTrue = Array.TrueForAll(isFind, delegate(bool b) { return b; });

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 838066

If you have .NET 3.5 or higher you can use Enumerable.Any:

isFind.Any(x => !x)

From your update to the question you are using .NET 2.0 so writing out the loop is probably the best option.

Upvotes: 2

Related Questions