這個例子純粹是爲了學習,否則我會馬上使用Lambda表達式。如何在不使用lambda的情況下使用linq擴展?
我想嘗試使用沒有lambda的Where()擴展方法來查看它的外觀,但我無法弄清楚如何讓它編譯和正常工作。這個例子沒有意義,所以不要試圖找出任何邏輯。
我基本上只想知道是否可以使用擴展方法而不使用lambda(僅用於學習目的)以及代碼中的外觀如何。
我所困惑的是Where()條件需要Func<int,bool>
,但該方法返回IEnumerable<int>
? Func的定義方式是,它接受一個int並返回一個布爾值。它將使我更有意義,如果這是Func<int, bool, IEnumberable<string>>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegates
{
public class Learning
{
/// <summary>
/// Predicates - specialized verison of Func
/// </summary>
public static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
Func<int, bool> someFunc = greaterThanTwo;
IEnumerable<int> result = list.Where(someFunc.Invoke(1));
}
static IEnumerable<int> greaterThanTwo(int arg, bool isValid)
{
return new List<int>() { 1 };
}
}
}
更新的代碼
public class Learning
{
/// <summary>
/// Predicates - specialized verison of Func
/// </summary>
public static void Main()
{
// Without lambda
List<int> list = new List<int> { 1, 2, 3 };
Func<int, bool> someFunc = greaterThanTwo;
// predicate of type int
IEnumerable<int> result = list.Where(someFunc);
}
static bool greaterThanTwo(int arg, bool isValid)
{
return true;
}
}
我得到以下錯誤:
沒有重載 'greaterThanTwo' 匹配委託「System.Func '
看看這篇文章從MSDN。 http://msdn.microsoft.com/en-us/library/bb534803.aspx – 2011-05-24 23:10:33
如果您更新您的方法簽名以匹配Func的委託語法,您可能可以通過此方式傳遞它。 – 2011-05-24 23:12:17