標籤:
深度拷貝 List<string[]> 到一個新的List<string[]> 中(tempList),
遍曆tempList,移除原list中重複的string[],代碼如下:
static void Main(string[] args) { List<string[]> list = new List<string[]>(); list.Add(new string[]{"1","2","3"}); list.Add(new string[] { "1","2" ,"3"}); list.Add(new string[] { "1" }); list.Add(new string[] { "1" }); list.Add(new string[] { "1" }); var tempList = new List<string[]>(list); if (list.Count >= 2) //確保下標i不越界 { for (int i = 1; i < tempList.Count; i++) { if (string.Join(",", tempList[i]) == string.Join(",", tempList[i - 1])) { list.Remove(tempList[i]); } } } foreach (var item in list) { string s = string.Join(",", item); Console.WriteLine(s); } Console.ReadKey(); }
運行如下:
那麼問題又來了,挖掘機技術……呸! 如果是List<List<string[]>>的集合又該如何去重呢?
原理是一樣的把List<string[]>變成字串,裝到List<string>中,根據List<sting>重複的元素的下標索引,刪除原集合中重複的元素,
代碼如下:
static void Main(string[] args) { List<string[]> list = new List<string[]>(); list.Add(new string[]{"1","2","3"}); list.Add(new string[] { "1","2" ,"3"}); list.Add(new string[] { "1" }); list.Add(new string[] { "1" }); list.Add(new string[] { "1" }); List<string[]> list2 = new List<string[]>(); list2.Add(new string[] { "1", "2", "3" }); list2.Add(new string[] { "1", "2", "3" }); list2.Add(new string[] { "1" }); list2.Add(new string[] { "1" }); list2.Add(new string[] { "1" }); List<string[]> list3 = new List<string[]>(); list3.Add(new string[] { "1", "2", "3" ,"4","5"}); list3.Add(new string[] { "1", "2", "3" }); list3.Add(new string[] { "1" }); list3.Add(new string[] { "1" }); list3.Add(new string[] { "1" }); List<List<string[]>> superList = new List<List<string[]>>(); //集合list和集合list2是相同的 superList.Add(list); superList.Add(list2); superList.Add(list3); List<string> strList = new List<string>(); foreach (var d in superList) { StringBuilder sb = new StringBuilder(); foreach (var dd in d) { string s = string.Join(",", dd); sb.Append(s); } string str = sb.ToString(); strList.Add(str); //把superList中每個子項目拼接成一條字串放到strList中 } if (strList.Count >= 2) { for (int i = 1; i < strList.Count; i++) { if (strList[i] == strList[i - 1]) { superList.RemoveAt(i);//根據strList中重複的字串的下標索引,刪除superList中的元素 } } } Console.WriteLine(superList.Count()); Console.ReadKey(); }
View Code
運行如下:
List<string[]> 如何去重