使用扩展方法语法编写没有select或group子句的LINQ查询

时间:2017-06-18 10:57:22

标签: c# linq

我正在编写一个基于条件构建查询的函数。我想要做的是为每个条件设置不同的select语句(在单独的方法中查询,然后每个用户都可以拥有他自己的选择语句)。

有点像这样

var q = BuildQuery();
var nq = q.Select(...);
return nq.ToList();

使用扩展方法语法编写查询将解决'查询主体必须以select或group子句结束'。

这是我的查询

        return (from ScheduleItemAttendee SIA in context.ScheduleItemAttendees
               join AttendeeService AS in context.AttendeeServices on SIA.Id equals AS.AttendeeId into x
               from Att in x.DefaultIfEmpty()
               where (Att == null || !Att.IsDeleted)
               && !(SIA == null || SIA.IsDeleted)

               && ((string.IsNullOrEmpty(criteria.Keyword)) || (SIA.Individual.FullNameAr.Trim().ToLower().Contains(criteria.Keyword) || SIA.Individual.FullNameEn.Trim().ToLower().Contains(criteria.Keyword))));

1 个答案:

答案 0 :(得分:2)

试试这个:

public IQueryable<T> BuildQuery<T>(Expression<Func<ScheduleItemAttendee, AttendeeService, T>> selector)
{
    return
        from ScheduleItemAttendee SIA in context.ScheduleItemAttendees
        join AttendeeService AS in context.AttendeeServices on SIA.Id equals AS.AttendeeId into x
        from Att in x.DefaultIfEmpty()
        where (Att == null || !Att.IsDeleted)
            && !(SIA == null || SIA.IsDeleted)
            && ((string.IsNullOrEmpty(criteria.Keyword))
                || (SIA.Individual.FullNameAr.Trim().ToLower().Contains(criteria.Keyword)
                || SIA.Individual.FullNameEn.Trim().ToLower().Contains(criteria.Keyword)))
        select selector(SIA, null);
}

然后像这样使用它:

var q = BuildQuery((sia, att) => 42);

(在42的位置放置一些有意义的东西。)