最近在项目上写的方法,想通过减少访问数据层,将需要重复调用的值存入List,无意中碰到的一个巨坑,至今仍不明所以,在此写出来,一来是看看有没有同道中人,二来是看看有没有大牛能解惑。
逻辑如下:
1、从数据库中获取AList(yycfList)
2、new一个BLis(_yycfList),将AList中的部分值赋予它
3、改变BList中的值
4、AList的值也变了
代码如下:
1 List<A> AList = GetAList(); 2 List<X> XList = GetXList(); 3 List<Y> YList = GetYList(); 4 foreach (var y in YList) 5 { 6 List<A> BList = AList.FindAll(x => x.CustomType == y.CustomType); 7 if (y.IsPrivate || y.IsSustainable) 8 { 9 foreach (var b in BList)10 {11 X _x = XList.Find(x => x.Curve == b.Curve &&12 x.CustomType == b.CustomType &&13 x.FixType == (y.IsSustainable ? 2 : 1));14 if (_x != null)15 {16 17 b.AFactor = b.AFactor + _x.DRange / 100; //此处修改后直接影响AList的值 18 b.CFactor = b.CFactor + ((_x.URange - _x.DRange) / 5 / 100);19 }20 }21 }22 }
最终解决代码:
1 List<A> AList = GetAList(); 2 List<X> XList = GetXList(); 3 List<Y> YList = GetYList(); 4 foreach (var y in YList) 5 { 6 List<A> BList = AList.FindAll(x => x.CustomType == y.CustomType); 7 8 if (y.IsPrivate || y.IsSustainable) 9 {10 BList = new List<A> (); //此处重新New BList11 foreach (var b in AList.FindAll(x => x.CustomType == y.CustomType))12 {13 X _x = XList.Find(x => x.Curve == b.Curve &&14 x.CustomType == b.CustomType &&15 x.FixType == (y.IsSustainable ? 2 : 1));16 B _b = new B(); //此处New一个B17 if (_x != null)18 {19 _b.AFactor = b.AFactor + _x.DRange / 100;20 _b.BFactor = b.BFactor;21 _b.CFactor = b.CFactor + ((_x.URange - _x.DRange) / 5 / 100);22 BList.Add(_b); //将改变后的B加入List23 }24 else25 {26 BList.Add(b); //无需改变则将旧B加入List27 }28 }29 }30 }