2013-05-15 44 views
0

我想遍歷對象列表並檢查一個布爾值,直到所有的都爲真,然後返回。Linq如何只有在滿足條件時才返回?

這可能與Linq?

換句話說:

的< OBJ列表{1,TRUE},OBJ {1,FALSE},OBJ {1,FALSE},OBJ {1, 假} >

但布爾正在更新的東西,我想檢查布爾,直到所有的都是真的,然後返回控制。

如何處理linq?

謝謝!

回答

3

您可以使用.Any()返回一個布爾值,以指示集合中的任何值爲false。

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

這將運行,直到所有變量設置爲true

+0

甜美簡單!謝謝。 – user1013388

0

由於你的集合正在更新,而你想不斷地檢查它,所以你需要將檢查邏輯和邏輯更新爲不同的線程。

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 
相關問題