List去重的三种种方法

编程入门 行业动态 更新时间:2024-10-26 14:32:31

List去重的<a href=https://www.elefans.com/category/jswz/34/1770022.html style=三种种方法"/>

List去重的三种种方法

List去重–C#

class List去重的方法//List如何去重{#region//自定义去重方法public static void Main() => useDistinctMethod();public static void diyMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person{ name= "李四" , password = "123456", age = 20 });list.Add(new Person{ name = "张三", password = "123456", age = 18 });list.Add(new Person{ name = "王五", password = "123456", age = 22 });list.Add(new Person{ name = "张三", password = "123456", age = 18 });// 去重操作List<Person> newList = new List<Person>(list.Count());list.ForEach(i=> {if (!newList.Contains(i)){ newList.Add(i);}});newList.ForEach(p => Console.WriteLine($"{ p.name },{ p.password },{ p.age }"));Console.ReadKey();}#endregion#region//用hashset唯一真值去重public static void useSetMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person { name = "李四", password = "123456", age = 20 });list.Add(new Person { name = "张三", password = "123456", age = 18 });list.Add(new Person { name = "王五", password = "123456", age = 22 });list.Add(new Person { name = "张三", password = "123456", age = 18 });// 去重操作HashSet<Person> newList = new HashSet<Person>(list);foreach (Person p in newList){Console.WriteLine($"{ p.name },{ p.password },{ p.age }");}Console.ReadKey();}#endregion#region//用Distinct去重public static void useDistinctMethod(){// 创建并给 List 赋值List<Person> list = new List<Person>();list.Add(new Person { name = "李四", password = "123456", age = 20 });list.Add(new Person { name = "张三", password = "123456", age = 18 });list.Add(new Person { name = "王五", password = "123456", age = 22 });list.Add(new Person { name = "张三", password = "123456", age = 18 });// 去重操作var newList = list.Distinct();foreach (Person p in newList){Console.WriteLine($"{ p.name },{ p.password },{ p.age }");}Console.ReadKey();}#endregion}struct Person{public String name { get; set; }public String password { get; set; }public int age { get; set; }}

更多推荐

List去重的三种种方法

本文发布于:2024-03-05 01:23:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1710945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:三种   种方法   List

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!