0

I want to loop over a list of objects and check a boolean value until all are true then return.

Is this possible with Linq??

In other words:

List of < obj {1, true}, obj {1, false}, obj {1, false}, obj {1, false} >

but the bool is being updated by something else and I want to check the bool until all are true then return control.

How to do with linq?

Thanks!

4

2 回答 2

3

You can return a boolean value using .Any() to indicate any of the values is false in your collection.

while( yourCollection.Any(q => q.BooleanVariable == false)) { }

This will run until all of the variables are set to true.

于 2013-05-15T00:42:00.077 回答
0

Since your collection is being updated while you want to continuously check it, you will need to separate the checking logic and logic which updates the list into different threads.

AutoResetEvent waitEvent = new AutoResetEvent(false);

ThreadPool.QueueUserWorkitem
(
    work =>
    {
        while(true)
        {
            Thread.Sleep(TimeSpan.FromSeconds(1));
            if(!yourCollection.Any(x => x.BooleanVariable == false))
            {
                waitEvent.Set();
                break;
            }
        }
    }
);

//alternatively, you could already have another thread running that is updating the list
new Thread(
{
    //do some stuff that updates the list here
}).Start();

waitEvent.WaitOne();

//continue doing stuff when all items in list are true
于 2013-05-15T00:57:38.007 回答