簡體   English   中英

Linq TakeWhile在循環中,僅給出第一個結果

[英]Linq TakeWhile in loop, giving only first result

我在循環中使用了takewhile語句,它僅在循環的第一次迭代中給出結果。 所有后續迭代都不會產生結果,即使我希望它們能夠產生結果。

例如下面的代碼。 第一次迭代將給出字符串a =“ blah1blah2blah3”。 在第二次迭代中,我期望a =“ blah2blah3”,但是需要的時間卻沒有給出a =“”,它沒有任何元素。

在現實世界中,這是一個很大的邏輯循環,因此我無法承擔超出循環的時間。 我試過使用count()和take()的組合,但是count()給出了所有符合條件的元素,而不是符合條件的項目計數,直到條件為假。

任何幫助將是有用的,謝謝。

碼:

public void blah()
{
    List<testclass> someStrings = new List<testclass>() 
    { new testclass() { name = "blah1", testNum = 1 },
      new testclass() { name = "blah2", testNum = 2 },
      new testclass() { name = "blah3", testNum = 3 },
      new testclass() { name = "none4", testNum = 4 },
      new testclass() { name = "blah5", testNum = 5 },
      new testclass() { name = "blah6", testNum = 6 },
      new testclass() { name = "none7", testNum = 7 } 
    };

    foreach (testclass tc in someStrings)
    {
       string a = string.Join("", someStrings.TakeWhile(i => i.name.Contains("blah") 
                           && i.testNum >= tc.testNum).Select(g => g.name.ToString()));
    }
}

我不確定您要從中實現什么,但是代碼的問題是,當您第二次執行循環時,即對於testNum2您的查詢如下所示:-

string a = someStrings.Where(i => i.name.Contains("blah")
                                    && i.testNum >= 2).Select(g => g.name.ToString());

因此,顯然第一個條件本身將失敗,即,對於包含1第一個元素, i.testNum >= 2 ,您將不會獲得任何結果或String.Empty作為輸出。

據我了解,您可以按照@CodeDennis的建議添加之前的SkipWhile來跳過以前的記錄,從而實現所需的目標:-

string a = string.Join("", someStrings.SkipWhile(i => i.testNum < tc.testNum)
            .TakeWhile(i => i.name.Contains("blah") && i.testNum >= tc.testNum)
            .Select(g => g.name.ToString()));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM