简体   繁体   中英

How to chain Linq methods dynamically in C#?

I working with MongoDB driver and I have the following classes:

public class Transactions
{
    public ObjectId Id { get; set; }
    public int UserId { get; set; }
    public int AccountId { get; set; }
    public int SettingId { get; set; }
}
public class Account
{
    public int Id {get; set;}
    public int Name {get; set;}
}
public class User
{
    public int Id {get; set;}
    public int Name {get; set;}
}
public class Setting
{
    public int Id {get; set;}
    public int Name {get; set;}
}

And I want form this, depending of the input of user:

var docs = collection.Aggregate()
                     .Lookup("account", "AccountId", "_id", "asAccounts")
                     .Lookup("user", "UserId", "_id", "asUsers")
                     .Lookup("setting", "SettingId", "_id", "asSettings")
                     .As<BsonDocument>()
                     .ToList();

That is, if the user just wanna the relation with account, form this:

var docs = collection.Aggregate()
                         .Lookup("account", "AccountId", "_id", "asAccounts")
                         .As<BsonDocument>()
                         .ToList();

Or if him wanna the relation with account and user:

var docs = collection.Aggregate()
                         .Lookup("user", "UserId", "_id", "asUsers")
                         .Lookup("setting", "SettingId", "_id", "asSettings")
                         .As<BsonDocument>()
                         .ToList();

It I trying to do is form the query depending the needs of user. Just wanna know how to chain the methods in runtime.

You can create your dynamic chain using some conditional tests to prepare the query:

var docs = collection.Aggregate();

if ( WantRelationWithAccount )
  docs = docs.Lookup("account", "AccountId", "_id", "asAccounts")

if ( WantRelationWithUser )
  docs = docs.Lookup("user", "UserId", "_id", "asUsers")

if ( WantSettings )
  docs = docs.Lookup("setting", "SettingId", "_id", "asSettings")

var result = docs.As<BsonDocument>().ToList();

But remember that order of operations in the chain is as added.

Linq queries are deferred executed, that means they are only executed when used like with a loop or a any method that causes the execution like ToList .

There is a linq ToLookup method but not Lookup , and it causes the query execution.

Does ToLookup forces immediate execution of a sequence

Perhaps you use extension methods provided by a special framework.

In anyway, staging execution does not prevent you from create the chain as exposed previously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM