Using Lambda Expressions trees with IEnumerable

Posted by Loathian on Stack Overflow See other posts from Stack Overflow or by Loathian
Published on 2010-03-07T20:41:18Z Indexed on 2010/03/08 9:21 UTC
Read the original article Hit count: 439

Filed under:
|
|
|
|

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; }
}

This results in the following error:

The type arguments for method 'System.Linq.Enumerable.Where(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

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?

© Stack Overflow or respective owner

Related posts about expression

Related posts about tree