首页 > 解决方案 > c# 无法转换 system.collections.generic.icollection到 KMSEntities.PMRUnitTypes

问题描述

我正在对我们的一个页面进行故障排除,我发现了一个 feachloop,其中嵌套了 foreach 循环,而不是嵌套它们,我打算对 foreach 循环进行多线程处理并单独分解它们

List<int> buildings = new List<int>();
            List<int> wings = new List<int>();
            List<int> complexes = new List<int>();
            List<int> unittypes = new List<int>();
            int floors = 0;
            int unitcnt = 0;
            ICollection<PMRUnitTypes> units = new List<PMRUnitTypes>();
            List<PMRProjectConfig> UnityTypesObj = new List<PMRProjectConfig>();


            //for each config in the project, get the summay

            foreach (var c in prj.Configs)
            {
                //add the buildings
                if (c.PB_ID.HasValue && buildings.FirstOrDefault(b => b == c.PB_ID.Value) <= 0)
                    buildings.Add(c.PB_ID.Value);

                //add the complexs
                if (c.PC_ID.HasValue && complexes.FirstOrDefault(co => co == c.PC_ID.Value) <= 0)
                    complexes.Add(c.PC_ID.Value);

                //add the wings
                if (c.PW_ID.HasValue && wings.FirstOrDefault(w => w == c.PW_ID.Value) <= 0)
                    wings.Add(c.PW_ID.Value);

                //add the floors
                if (c.Floor_ID.HasValue)
                    floors++;

                UnityTypesObj.Add(c.UnitTypes);

                //add the unit type codes
                foreach (var ut in c.UnitTypes)
                {
                    if (unittypes.FirstOrDefault(utc => utc == ut.PUTC_ID) <= 0)
                        unittypes.Add(ut.PUTC_ID);
                }

                //get the units
                var dscnt = DataServiceLocator.RunStoreProcedureReturnDS("GetPMRUnitsCountFromConfig", 200, new SqlParameter[]{
                    new SqlParameter{ParameterName = "@PPC_ID", Value= c.PPC_ID}
                });

                foreach (DataRow r in dscnt.Tables[0].Rows)
                {
                    unitcnt += int.Parse(r["unitCount"].ToString());
                }
            };

这是我的代码,但是在第二个 foreach 循环中,我没有这样做,而是尝试将其添加到列表中,然后在初始代码完成后循环遍历它,但是使用 ICollection 时出现上述错误。我发现 PMRUnittypes 是配置的 ICollection,但是有没有可能的方法来做到这一点或写得更好,这会加快代码的速度?

错误出现 UnityTypesObj.Add(c.UnitTypes);并且 proj.configs 来自数据库 var cust =DataServiceLocator.GetCustomer_DAO().GetCustomerByID(customerID, Context);

标签: c#

解决方案


由于c.UnitTypes是一个集合,您需要使用 AddRange 代替:

UnityTypesObj.AddRange(c.UnitTypes);

推荐阅读