使用Lambda表达式与IEnumerable树 [英] Using Lambda Expressions trees with IEnumerable

查看:146
本文介绍了使用Lambda表达式与IEnumerable树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试更多地了解如何使用Lamba表达式树,因此我创建了一个简单的例子。这是代码,这个工作在LINQPad如果粘贴在一个C#程序。

I've been trying to learn more about using Lamba expression trees and so I created a simple example. Here is the code, this works in LINQPad if pasted in as a C# program.

void Main()
{
    IEnumerable<User> list = GetUsers().Where(NameContains("a"));
    list.Dump("Users");
}

// Methods
public IEnumerable<User> GetUsers()
{
    yield return new User{Name = "andrew"};
    yield return new User{Name = "rob"};
    yield return new User{Name = "chris"};
    yield return new User{Name = "ryan"};
}

public Expression<Func<User, bool>> NameContains(string namePart)
{
    return u => u.Name.Contains(namePart);
}

// Classes
public class User
{
    public string Name { get; set; }
}

导致以下错误:


方法'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable,System.Func)'的类型参数不能从使用推断出来。尝试显式指定类型参数。

但是,如果我只是用main替​​换第一行:

However if I just substitute the first line in main with this:

IEnumerable<User> list = GetUsers().Where(u => u.Name.Contains("a"));

它工作正常。可以告诉我我在做什么错吗?

It works fine. Can tell me what I'm doing wrong, please?

推荐答案

Enumerable.Where 方法需要一个 Func< T,bool> ,而不是一个表达式< Func< T,bool>> 。也许你对 Queryable.Where 感到困惑,它将表达式作为参数...在你的情况下,你不需要一个表达式,你只需要一个代理可以对序列中的每个项执行。表达式的目的是(主要)被分析并转换为其他东西(例如SQL),以根据外部数据源执行查询

The Enumerable.Where method takes a Func<T, bool>, not an Expression<Func<T, bool>>. Perhaps you're confusing with Queryable.Where, which does take an expression as a parameter... In your case you don't need an expression, you just need a delegate that can be executed against each item in the sequence. The purpose of expressions is (mostly) to be analysed and translated to something else (SQL for instance), to perform the query against an external data source

这篇关于使用Lambda表达式与IEnumerable树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆