dotnetnoob
dotnetnoob

Reputation: 11330

Linq using predicate not working

I've created a small test class, that returns data from an xml file.

I now want to make it more dynamic using linq but cannot get it to work.

public class LenderCollection
{
    string fileName = "C:\\Lenders.xml";

    public IEnumerable<Lender> Lenders { get; set; }

    public void FetchLenders(Expression<Func<Lender, bool>> predicate = null)
    {
        IEnumerable<Lender> lenders = XmlHelper.GetObjectFromXml<List<Lender>>(fileName, "AllLenders");

        Lenders =  predicate.IsNotNull() ? lenders.Where(predicate) : lenders;

    }
}

Visual Studio is giving an error on the section "lenders.Where(predicate)" - the message is "... does not contain a definition for Where..."

Any ideas what I'm doing wrong?

* UPDATE *

It seems to be something to do with the predicate - .Where is avaialable otherwise.

Upvotes: 0

Views: 585

Answers (3)

Chris Dixon
Chris Dixon

Reputation: 9167

Replace:

lenders.Where(predicate)

With:

lenders.ToList().Where(predicate)

Both should be able to return IEnumerable.

The main downfall with this is that the query will execute on the .ToList() command. I guess this is down to what you expect your function to be doing though, and if this is acceptable for your needs.

Upvotes: 0

sloth
sloth

Reputation: 101072

There's no extension method Where that extends IEnumerable<T> and takes a parameter of type Expression<Func<T, bool>>.

You have two options:

  1. Use an IQueryable<Lender> instead of IEnumerable<Lender> (you can this easily by just calling .AsQueryable()) if you wan to keep the parameter predicate as Expression<Func<Lender, bool>>

  2. Use the type Func<Lender, bool> instead of Expression<Func<Lender, bool>> for the predicate parameter. Since you're loading your data from a file, there's no point in using an IQueryable over an IEnumerable.

Upvotes: 5

PhonicUK
PhonicUK

Reputation: 13864

It's complaining that whatever type lenders is does not have a .Where method. This is either because:

  • You haven't included using System.Linq;
  • The type of lenders isn't an IEnumerable or similar.

Upvotes: 0

Related Questions