c#代码重构与迭代(一)——循环代码的优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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 ?? "" ); }); |
优化说明:
- 使用Parallel.ForEach并行循环,这样能够同时处理多个元素,提高代码执行效率;
- 并行循环还需要保证线程安全,所以在循环体内部不要修改共享资源;
- 优化方式与之前相同,对列表中每个元素进行逐一处理,并简化代码逻辑。
- 将DevicesLogic、UserGroupRelationLogic和PersonProfileLogic实例化放在循环外部,避免在每次迭代中重复实例化;
- 使用var关键字提高代码可读性和简洁性;
- 简化addr变量赋值逻辑;
- 改善条件语句if(ur != null && _Device != null && model.UserID != _Device.UserID && !ur.NickName.IsNullOrEmpty())的结构;
- 简化deviceName变量赋值逻辑。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构