C#_List的使用_List重複添加值的錯誤避免修正
List的使用
程式碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lists_and_Generics
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("=========int List===========");
List<int> iList = new List<int>();
iList.Add(2);//0
iList.Add(3);//1
iList.Add(5);//2
iList.Add(7);//3
iList.Insert(2, 865);
foreach (int num in iList)
{
Console.WriteLine(num);
}
Console.WriteLine("=========string List===========");
//----------------------------------------
List<string> colors = new List<string>();
colors.Add("Red");
colors.Add("Blue");
colors.Add("Green");
foreach (string color in colors)
{
Console.WriteLine(color);
}
Console.WriteLine("=========double List===========");
List<double> douArray = new List<double>();
douArray.Add(0.2);
douArray.Add(0.4);
douArray.Add(0.6);
foreach(double douNum in douArray)
{
Console.WriteLine(douNum);
}
Console.ReadKey();
}
}
}
List重複添加值的錯誤避免修正
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Lists_and_Generics
{
class Program
{
static void Main(string[] args)
{
//new一個用List接的Model
List<myClass> ModelInfoList = new List<myClass>();
//會覆蓋的主因
//myClass isModelInfo = new myClass();
decimal addA = 1, addB = 2, addC = 3;
for(int i=0;i<3;i++)
{
////加在此,每次迴圈跑時,重新new一次,如此不會讓ModelInfoList 的資料被覆蓋
myClass isModelInfo = new myClass();
addA++;
addB++;
addC++;
//每次迴圈Model的每個欄位都增加新的資訊
isModelInfo.FieldA = addA;
isModelInfo.FieldB = addB;
isModelInfo.FieldC = addC;
//將每次迴圈紀錄的欄位Model,add到List接的Model
ModelInfoList.Add(isModelInfo);
}
Console.ReadKey();
}
}
}
參考:
為什麼List 在add數次,總會被最後add的項目給覆蓋呢?
http://ww0o0ww.pixnet.net/blog/post/63051673-%E3%80%90c%23%E3%80%91%E3%80%8Alist-%3Ct%3E%E3%80%8Blist-add-%E8%A6%86%E8%93%8B%E5%8E%9F%E4%BE%86%E7%9A%84%E8%B3%87%E6%96%99
http://csharp.net-informations.com/collection/list.htm
https://www.youtube.com/watch?v=Kx8ij3WZpSg
http://stackoverflow.com/questions/14433332/avoid-adding-duplicate-elements-to-a-list-c-sharp
http://stackoverflow.com/questions/347675/list-add-seems-to-be-duplicating-entries-whats-wrong
留言
張貼留言