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)
If you're using .NET2 then you can use the static TrueForAll
method:
bool allTrue = Array.TrueForAll(isFind, delegate(bool b) { return b; });
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.
.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.
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.
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
}
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
}
精彩评论