c# List使用中遇到的問題


最近在項目上寫的方法,想通過減少訪問數據層,將需要重復調用的值存入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 BList
11         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一個B
17             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加入List
23             }
24             else
25             {
26                 BList.Add(b);   //無需改變則將舊B加入List
27             }
28         }
29     }
30 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM