何可以將for語句轉換爲LINQ嗎?如何將FOR語句轉換爲LINQ
假設我有一個方法。
public void Method_One(){
//...code...
//...code...
}
而且我必須多次調用這些代碼,迭代次數也是我的參數。
for(int i = 0; i < numbers.Length; ++i){
Method_One();
}
我知道有foreach-statement的轉換,但FOR怎麼樣?
何可以將for語句轉換爲LINQ嗎?如何將FOR語句轉換爲LINQ
假設我有一個方法。
public void Method_One(){
//...code...
//...code...
}
而且我必須多次調用這些代碼,迭代次數也是我的參數。
for(int i = 0; i < numbers.Length; ++i){
Method_One();
}
我知道有foreach-statement的轉換,但FOR怎麼樣?
當你可以使用foreach
你可以使用永諾和for
也因此一個簡單的LINQ(asuming numbers
是List
):否則,它使用IEnumerable<T>.ToList()
之前轉換到一個列表。
numbers.ForEach(Method_One)
即相當於
numbers.ForEach(x => Method_One());
而且也:
foreach(int i in numbers) Method_one();
您可以使用:
numbers.ForEach(num =>
{
MethodOne();
});
如果你需要將CURENT號傳遞到功能,它將是
MethodOne(num);
Enumerable.Range(0, numbers.Length).ToList().ForEach(arg => Method_One());
同意@Ivan Stoev,它仍然是一個周圍使用LINQ做事情的方式。
而不是Linq一個簡單的輔助靜態方法應該使其更具可讀性。
public static void Repeater(int count, Action action)
{
Debug.Assert(action!=null);
for (int i = 0; i < count; i++)
action();
}
//Use it like this
Repeater(10, Method_One);
什麼是ForEach這裏? – ASh
嗯,'IEnumerable
如果你想使用ForEach,你可以添加'ToList()',但它仍然是一個過度殺傷 –
如果你想力 LINQ的做一些事情,然後兌現:
Enumerable
.Range(0, numbers.Length)
.Select(item => {
Method_One(); // you may want Method_One(item);
return 0; // you have to return something
})
.ToList(); // materialization, to make Linq do
然而,LINQ的尚未設計用於這種用途等的查詢看起來醜陋。像
foreach (var item in numbers)
Method_One(); // you may want Method_One(item);
環路遠遠更好代碼。
爲什麼標記ReSharper?該工具應該告訴你如何轉換它。 – HimBromBeere
LINQ不是'for/foreach'替換。用於查詢,而不是調用動作。 –