Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

lambda

mongodb

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

like image 837
Abdul Sheikhsalem Avatar asked Sep 17 '25 17:09

Abdul Sheikhsalem


1 Answers

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");
like image 194
Nkosi Avatar answered Sep 19 '25 07:09

Nkosi