C# 合并只要有交集的所有集合
程序员文章站
2022-06-21 16:07:28
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace ConsoleApp ......
1 using system; 2 using system.collections.generic; 3 using system.linq; 4 using system.text; 5 using system.threading.tasks; 6 7 namespace consoleapplication2 8 { 9 class program 10 { 11 static void main(string[] args) 12 { 13 14 list<int> list1 = new list<int> { 1, 2, 3 }; 15 list<int> list2 = new list<int> { 4, 5, 6 }; 16 list<int> list3 = new list<int> { 1, 4, 7 }; 17 18 19 list<int> list4 = new list<int> { 10, 11, 12 }; 20 list<int> list5 = new list<int> { 13, 11, 14 }; 21 22 23 list<int> list6 = new list<int> { 16, 17, 18 }; 24 list<int> list7 = new list<int> { 18, 19, 20 }; 25 26 list<list<int>> list = new list<list<int>>(); 27 list.add(list1); 28 list.add(list2); 29 list.add(list3); 30 list.add(list4); 31 list.add(list5); 32 list.add(list6); 33 list.add(list7); 34 35 list<int> allint = new list<int>();//所有的集合数据 36 hashset<int> repeated = new hashset<int>(); //得到没有重复的hashset 37 foreach (list<int> item in list) 38 { 39 foreach (int index in item) 40 { 41 if (allint.contains(index)) 42 repeated.add(index);//得到所有重复的集合的元素 43 allint.add(index);//得到所有的集合的元素 44 } 45 } 46 47 48 foreach (var setkey in repeated)//循环重复的值 49 { 50 list<int> templist = null;//临时 51 list<list<int>> removelist = new list<list<int>>(); 52 foreach (var item in list)//循环 53 { 54 //if (templist == null) 55 //{ 56 // templist = item; 57 // removelist.add(item); 58 //} 59 60 //if (item.contains(setkey)) 61 //{ 62 // removelist.add(item); 63 // templist = templist.union(item).tolist(); 64 //} 65 66 if (item.contains(setkey)) 67 { 68 if (templist == null) 69 { 70 templist = item; 71 removelist.add(item); 72 } 73 else 74 { 75 removelist.add(item); 76 templist = templist.union(item).tolist(); 77 } 78 } 79 } 80 foreach (var item in removelist) 81 { 82 list.remove(item); 83 } 84 removelist.clear(); 85 list.add(templist); 86 } 87 88 foreach (var item in list) 89 { 90 foreach (var item1 in item) 91 { 92 console.write(item1 + " , "); 93 } 94 console.write("\r\n"); 95 } 96 console.readkey(); 97 } 98 99 100 } 101 }
上一篇: Jenkins与SVN持续集成的示例代码