語法優化-多條件判斷
阿新 • • 發佈:2019-01-05
結合專案
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 = fromp 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: }
無論多引數還是單一引數,都可以 以此思想拓展,合適你的需求即可。