这个例子纯粹是为了学习,否则我会马上使用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