C# 链表去重 List 一维 二维 分别使用 Distinct() GroupBy() 方法
分别使用过List中Distinct(),GroupBy()实现链表的去重。
1.先上效果:
一维链表中分别有元素“aa”,"bb",'aa','aa',"cc",使用Distinct()方法后输出 aa,bb,cc
二维链表中类型为ClassA类型,其中对象的属性A分别为1,1,2,3,1,使用GroupBy()方法实则是分类,输出Key值分别为1,2,3。
2.上代码,类ClassA
class ClassA { private int a; public int A { get { return a; } set { a = value; } } private string b; public string B { get { return b; } set { b = value; } } }
主函数,分别打印一维链表,二维链表去重后输出的值。
1 static void Main(string[] args) 2 { 3 //1.一维链表去重复(Distinct方法) 4 List<string> lst1 = new List<string>() { "aa", "bb", "cc", "aa", "bb" }; 5 List<string> lst1Distinct = lst1.Distinct().ToList(); 6 7 StringBuilder sb1 = new StringBuilder(); 8 sb1.Append("一维链表去重:"); 9 foreach (var item in lst1Distinct) 10 { 11 sb1.Append(item); 12 sb1.Append("-"); 13 } 14 Console.WriteLine(sb1.ToString());//结果为 aa-bb-cc- 15 16 //2.二维链表去重(GroupBy方法) 17 List<ClassA> lst2 = new List<ClassA>(); 18 lst2.Add(new ClassA() { A = 1, B = "aa" }); 19 lst2.Add(new ClassA() { A = 1, B = "bb" }); 20 lst2.Add(new ClassA() { A = 2, B = "aa" }); 21 lst2.Add(new ClassA() { A = 3, B = "aa" }); 22 lst2.Add(new ClassA() { A = 1, B = "cc" }); 23 var lst2Distinct = lst2.GroupBy(r => r.A);//根据属性A分组 24 StringBuilder sb2 = new StringBuilder(); 25 sb2.Append("二维链表去重:"); 26 foreach (var item in lst2Distinct) 27 { 28 sb2.Append(item.Key.ToString()); 29 sb2.Append("-"); 30 } 31 Console.WriteLine(sb2.ToString());//结果为1-2-3- 32 Console.Read(); 33 }
相关推荐
koushr 2020-11-12
范范 2020-10-28
zhaochen00 2020-10-13
Mars的自语 2020-09-27
steeven 2020-09-18
kka 2020-09-14
qiangde 2020-09-13
聚沙成塔积水成渊 2020-08-16
earthhouge 2020-08-15
aanndd 2020-08-12
范范 2020-07-30
bluetears 2020-07-28
mingyunxiaohai 2020-07-19
horizonheart 2020-07-19
liushall 2020-07-18
bluetears 2020-07-05
fengshantao 2020-07-02
liuweixiao0 2020-06-27