[英]Use List as parameter in a Func delegate
我想知道是否可以使用 List 作為標准 Func 的參數。
示例代碼(這不起作用):
Func<List<int>, int> convert =
(list_name) => x-2;
如果可能的話,我只想在 Func 中使用 List 作為參數。
E : 可能的重復確實有助於回答問題。 但是在我的問題中,我想知道如何在 Func 中使用 List 和 Lambda 表達式。 嘗試對列表做出反應時是否必須使用 foreach 是否可以用其他東西?
我想您希望為列表中的每個元素執行委托。 所以你還應該返回一個整數列表。
Func<int, int> f = x => x - 2;
Func<List<int>, List<int>> myFunc = x => x.Select(f).ToList();
現在你可以調用它:
var l = new List<int> { 3, 5, 4, 9 };
var result = myFunc(l);
看我的小提琴。
編輯:當您想向Func
提供x - 2
部分時,您還必須使用具有三個通用類型參數的 Func:一個用於列表,第二個用於表達式,最后一個作為返回值:
Func<List<int>, Func<int, int>, List<int>> myFunc = (x, y) => x.Select(y).ToList();
var result = myFunc(l, x => x - 2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.