2 回答

TA貢獻1802條經驗 獲得超10個贊
有兩個覆蓋 linq where。
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
您調用使用第二個參數int類型值意味著您的數組索引。
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, int, bool> predicate);
這將返回集合中索引值小于或等于 2 的值。
Where ((string n, int i)=> {return i++ <=2;})
但是i++沒有意義,因為您離開了委托函數范圍,自動增量 i 的值不保留

TA貢獻1815條經驗 獲得超13個贊
我的期望是每次調用委托都會傳遞一個新參數。我知道由于閉包,在 lambda 表達式中使用的局部變量在所有調用中都會保留,但這是一個參數。
在調用之間不保留該參數。然而,第二個參數 (the int i) 是一個index,因此它由函數本身的邏輯遞增.Where(..)。
在Where它看起來或多或少像:
public static IEnumerable<T> Where(this IEnumerable<T> data, Funct<T, int, bool> p) {
int i = 0;
foreach(T t in data) {
if(p(t, i)) {
yield return t;
}
i++;
}
}
注意:如果我們檢查源代碼,我們會看到它委托給WhereIterator執行邏輯的函數。我聽說提供了一個更“干凈”的實現來解釋這個想法。
請注意i++:在索引遞增由所述Where功能。不管i函數中的做了什么,我們每次都用另一個值調用它。Anint不是引用對象,因此您無法更新數字的“狀態”。
以下面的調用為例:
csharp> arrayOne.Where ((string n, int i)=> {i += 2; return i <= 4;} )
{ "One", "Two", "Three" }
在這里,我們增加i用2,我們看到的確是低于指數2(由兩個或指數增加是小于4)仍然是相同的。因此指數并沒有讓兩個或三個跳。
- 2 回答
- 0 關注
- 176 瀏覽
添加回答
舉報