c#代码重构与迭代(一)——循环代码的优化

  foreach (var item in list)
            {
                Devices _Device = DevicesLogic.GetInstance().GetDevices(item.DeviceID);
                string addr = item.Address;
                if (addr.Trim() == "")
                {
                    addr = LocationAPI.GetAddressNew(item.OLat, item.OLng);
                }
                var ur = UserGroupRelationLogic.GetInstance().GetDeviceGroup(item.DeviceID, model.UserID);
                var profile = PersonProfileLogic.GetInstance().GetProfileByDevice(item.DeviceID);
                string Nickname = "";
                if (profile != null)
                    Nickname = profile.Nickname ?? "";
                if (ur != null && _Device != null && model.UserID != _Device.UserID && !ur.NickName.IsNullOrEmpty())
                {
                    Nickname = ur.NickName;
                }
           }

 

var deviceLogic = DevicesLogic.GetInstance();
            var userGroupRelationLogic = UserGroupRelationLogic.GetInstance();
            var personProfileLogic = PersonProfileLogic.GetInstance();

            Parallel.ForEach(list, (item) =>
            {
                var deviceId = item.DeviceID;
                var device = deviceLogic.GetDevices(deviceId);
                if (device == null || model.UserID == device.UserID) return;

                var address = string.IsNullOrWhiteSpace(item.Address) ? LocationAPI.GetAddressNew(item.OLat, item.OLng) : item.Address;

                var deviceGroup = userGroupRelationLogic.GetDeviceGroup(deviceId, model.UserID);
                var nickname = deviceGroup != null && !string.IsNullOrWhiteSpace(deviceGroup.NickName)
                    ? deviceGroup.NickName
                    : (personProfileLogic.GetProfileByDevice(deviceId)?.Nickname ?? "");

            });

  

优化说明:

  1. 使用Parallel.ForEach并行循环,这样能够同时处理多个元素,提高代码执行效率;
  2. 并行循环还需要保证线程安全,所以在循环体内部不要修改共享资源;
  3. 优化方式与之前相同,对列表中每个元素进行逐一处理,并简化代码逻辑。
  4. 将DevicesLogic、UserGroupRelationLogic和PersonProfileLogic实例化放在循环外部,避免在每次迭代中重复实例化;
  5. 使用var关键字提高代码可读性和简洁性;
  6. 简化addr变量赋值逻辑;
  7. 改善条件语句if(ur != null && _Device != null && model.UserID != _Device.UserID && !ur.NickName.IsNullOrEmpty())的结构;
  8. 简化deviceName变量赋值逻辑。

 

posted @ 2023-04-22 15:42  GroundSoft  阅读(15)  评论(0编辑  收藏  举报