2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超10個(gè)贊
有兩個(gè)覆蓋 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);
您調(diào)用使用第二個(gè)參數(shù)int類型值意味著您的數(shù)組索引。
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++沒有意義,因?yàn)槟x開了委托函數(shù)范圍,自動(dòng)增量 i 的值不保留

TA貢獻(xiàn)1815條經(jīng)驗(yàn) 獲得超13個(gè)贊
我的期望是每次調(diào)用委托都會(huì)傳遞一個(gè)新參數(shù)。我知道由于閉包,在 lambda 表達(dá)式中使用的局部變量在所有調(diào)用中都會(huì)保留,但這是一個(gè)參數(shù)。
在調(diào)用之間不保留該參數(shù)。然而,第二個(gè)參數(shù) (the int i) 是一個(gè)index,因此它由函數(shù)本身的邏輯遞增.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++;
}
}
注意:如果我們檢查源代碼,我們會(huì)看到它委托給WhereIterator執(zhí)行邏輯的函數(shù)。我聽說提供了一個(gè)更“干凈”的實(shí)現(xiàn)來解釋這個(gè)想法。
請(qǐng)注意i++:在索引遞增由所述Where功能。不管i函數(shù)中的做了什么,我們每次都用另一個(gè)值調(diào)用它。Anint不是引用對(duì)象,因此您無法更新數(shù)字的“狀態(tài)”。
以下面的調(diào)用為例:
csharp> arrayOne.Where ((string n, int i)=> {i += 2; return i <= 4;} )
{ "One", "Two", "Three" }
在這里,我們?cè)黾觟用2,我們看到的確是低于指數(shù)2(由兩個(gè)或指數(shù)增加是小于4)仍然是相同的。因此指數(shù)并沒有讓兩個(gè)或三個(gè)跳。
- 2 回答
- 0 關(guān)注
- 175 瀏覽
添加回答
舉報(bào)