Abdul Sheikhsalem
Abdul Sheikhsalem

Reputation: 53

How do I insert a lambda expression as a parameter to a mongodb 'collection.find' method?

I am new to lambda expressions and delegates. I don't exactly know how to use them. So I have this method that I want to pass a lambda expression parameter to as such (x : x.name == "testName") so I can fetch Mongodb records that has "testname" as a name.

public List<BaseModel> get(*lambda expression here*)
    {


        List<User> users = Database.userCollectionObjs.Find(*lambda expression here*).ToList();
        List<BaseModel> baseModels = new List<BaseModel>();
        foreach (User user in users)
        {

            baseModels.Add(user);
        }

        return baseModels;

    }

obviously if I do it like this:

        List<User> users = Database.userCollectionObjs.Find(user => user.name == "testuser").ToList();

it works. but how do I pass this expression as a parameter to my get() and then insert it in the userCollectionObjs.Find

Upvotes: 4

Views: 721

Answers (1)

Nkosi
Nkosi

Reputation: 247443

That Find extension method is defined as

public static IFindFluent<TDocument, TDocument> Find<TDocument>(
    this IMongoCollection<TDocument> collection,
    Expression<Func<TDocument, bool>> filter, //<-- NOTE THE FILTER
    FindOptions options = null
)

Take note of the filter parameter's type.

You would need to pass the appropriate filter for your collection.

Assuming userCollectionObjs holds User then the get() would look something like

public List<BaseModel> get(Expression<Func<User, bool>> filter) {
    List<User> users = Database.userCollectionObjs.Find(filter).ToList();
    List<BaseModel> baseModels = new List<BaseModel>();
    foreach (User user in users) {
        baseModels.Add(user);
    }
    return baseModels;
}

This would then allow for the invocation of get function as desired

List<BaseModel> baseModels = myClass.get(user => user.name == "testuser");

Upvotes: 3

Related Questions