LINQ:拆分“或"条件 [英] LINQ: Split Where OR conditions

查看:68
本文介绍了LINQ:拆分“或"条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下条件

sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent)) ||
                                                   y.session.ROOM.ToUpper().Contains(SearchContent) ||
                                                   y.session.COURSE.ToUpper().Contains(SearchContent));

例如,我想根据字符串是否为空将其分成多行:

I want to split this into multiple lines based on whether a string is empty for example:

if (!String.IsNullOrEmpty(Division)) {
    sessions = sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent)));
}

if (!String.IsNullOrEmpty(Room)) {

    // this shoudl be OR
    sessions = sessions.Where(y => y.session.ROOM.ToUpper().Contains(SearchContent));
}

if (!String.IsNullOrEmpty(course)) {

    // this shoudl be OR
    sessions = sessions.Where(y => y.session.COURSE.ToUpper().Contains(SearchContent));
}

如果您注意到我要添加多个或"条件,请根据房间",课程"和分区"字符串是否为空来拆分.

If you notice I want to add multiple OR conditions split based on whether the Room, course, and Division strings are empty or not.

推荐答案

有几种解决方法:

  1. 每次都将"where"应用于原始查询,然后Union()将所得查询应用于

var queries = new List<IQueryable<Session>>();
if (!String.IsNullOrEmpty(Division)) {
    queries.Add(sessions.Where(y => y.session.SESSION_DIVISION.Any(x => x.DIVISION.ToUpper().Contains(SearchContent))));
}

if (!String.IsNullOrEmpty(Room)) {

    // this shoudl be OR
    queries.Add(sessions.Where(y => y.session.ROOM.ToUpper().Contains(SearchContent)));
}

if (!String.IsNullOrEmpty(course)) {

    // this shoudl be OR
    queries.Add(sessions.Where(y => y.session.COURSE.ToUpper().Contains(SearchContent)));
}

sessions = queries.Aggregate(sessions.Where(y => false), (q1, q2) => q1.Union(q2));

  • 执行表达式"操作以将lambda表达式的主体合并在一起,并通过OrElse表达式进行连接. (这很复杂,除非您已经有了库来帮助您:在加入主体之后,还必须遍历表达式树以替换参数表达式.它可能变得很粘.请参阅

  • Do Expression manipulation to merge the bodies of your lambda expressions together, joined by OrElse expressions. (Complicated unless you've already got libraries to help you: after joining the bodies, you also have to traverse the expression tree to replace the parameter expressions. It can get sticky. See this post for details.

    这篇关于LINQ:拆分“或"条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆