.NET的语法优化

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)
           {
               if ((number > 0) && (number >= 10) && (number % 2 > 0) && (number * 2 > 100))
                {
                     return true;
                 }
                return false;
   }

 改造后:

 private static bool UseFunc(int number)
           {
                var conditionlist = new List<Func<bool>>()
                {
                     () => number > 0,
                     () => number >= 10,
                     () => number % 2 > 0,
                     () => number * 2 > 100
               };
  
               return conditionlist.TrueForAll(foo => foo.Invoke());
            }

 

posted @ 2016-11-21 15:29  石shi  阅读(292)  评论(0编辑  收藏  举报