语法优化-多条件判断
结合项目
1.多参数
判断 条件
//判断 var fileKey = new { DateStart = search.DateStart.IsNull(), //关开始时间 DateEnd = search.DateEnd.IsNull(), //结束时间 UserName = search.UserName.IsNullOrEmpty(), //用户名 NickName = search.NickName.IsNullOrEmpty(), //昵称 PhoneNumber = search.PhoneNumber.IsNullOrEmpty(), //电话号码 ProblemCatey = search.ProblemCatey.IsNullOrEmpty(), //问题种类 };
IsNull() 和 IsNullOrEmpry() 是拓展静态方法
/// <summary> /// 验证字符串是否为空字符串 /// </summary> /// <param name="self"></param> /// <returns></returns> public static bool IsNullOrEmpty(this string self) { if (self == null || self.Length == 0) { return true; } return false; }
使用如下
//查询 var list = from p in unitOfWork.FeedBack.Get(p => (fileKey.ProblemCatey || p.ProblemCatey.Contains(search.ProblemCatey))) join m in unitOfWork.Member.Get() on p.UserID equals m.Id where fileKey.UserName || m.UserName.Contains(search.UserName) where fileKey.NickName || m.NickName.Contains(search.NickName) where fileKey.PhoneNumber || m.PhoneNumber.Contains(search.PhoneNumber) where fileKey.DateStart || p.CreatedOn >= search.DateStart where fileKey.DateEnd || p.CreatedOn <= search.DateEnd select new FeedBackModelExd { Id = p.Id, ProblemCatey = p.ProblemCatey, CreatedOn = p.CreatedOn, UserName = m.UserName, NickName = m.NickName, PhoneNumber = m.PhoneNumber, Content = p.Content, };
2.单一参数
改造前
private static bool TraditionalVerify(int number) 2: { 3: if ((number > 0) && (number >= 10) && (number % 2 > 0) && (number * 2 > 100)) 4: { 5: return true; 6: } 7: return false; 8: }
改造后
8: private static bool UseFunc(int number) 9: { 10: var conditionlist = new List<Func<bool>>() 11: { 12: () => number > 0, 13: () => number >= 10, 14: () => number % 2 > 0, 15: () => number * 2 > 100 16: }; 17: 18: return conditionlist.TrueForAll(foo => foo.Invoke()); 19: }
无论多参数还是单一参数,都可以 以此思想拓展,合适你的需求即可。