简体   繁体   中英

How to concat expression in linq query

I have a following code to create an expression:

Expression<Func<Process, bool>> exp = null;

if (condition)
{
    exp = x => x.Hierarchy.StartWith(hierarchy) && x.Level == 2;
}
/*
   other conditions that modify the exp variable
*/
else
{
    exp = x => x.Hierarchy == hierarchy && x.Level == 3;
}

This query can be a diferent according with some conditions. I will use this expression in the following query, but, I would like to concat the exp expression variable in the linq query, for sample:

var query = from p in queryable
            join c in confQueryable on p.Id equals c.Id
            where p.ParentId == parentProcessId && exp // AND exp here...
            let hasChild = p.Processes.Any()
            select new ViewModel
            {
               Code = p.Code,
               Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
               ParentId = p.Id,
               Value = p.Id.ToString(),
               HasChildren = hasChild, // use hasChild variable
            };

I cannot convert it to linq methods because I return a ViewModel not the entity. If I do it, I do not know how to use the join and let commands in linq methods.

This query will be executed in database with NHibernate.

How could I concat the Expression<Func<T, bool>> in a Linq query?

Thank you.

Why you can't use chain methods like this

var query =
    queryable
        .Where(exp)
        .Join(confQueryable, p => p.Id, c => c.Id, (p, c) => new {p, c})
        .Where(@t => p.ParentId == parentProcessId)
        .Select(@t => new {@t, hasChild = p.Processes.Any()})
        .Select(@t => new ViewModel
        {
            Code = p.Code,
            Text = string.Format("{0}: {1}", c.Name, p.Name), // use c variable
            ParentId = p.Id,
            Value = p.Id.ToString(),
            HasChildren = hasChild, // use hasChild variable
        });

I don't know about nHibernate, but for Entity Framework such linq query should work.

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