C# Distinct去重泛型List

2021-01-28 15:15

阅读:424

标签:class   key   group   int   sts   去重   get   write   code   

  • List去重
  • List去重
  • List去重

1. List去重

 List ilist = new List() { 1, 2, 3, 4, 2, 3 };
 ilist = ilist.Distinct().ToList();
 foreach (var item in ilist)
 {
    Console.WriteLine(item);
 }

技术图片

2. List去重

 List strList = new List() { "4", "4", "5", "6", "6" };
 strList = strList.Distinct().ToList();
 foreach (var item in strList)
 {
    Console.WriteLine(item);
 }

技术图片

3. List去重

 public class User
 {
   public int Id { get; set; }
   public string Name { get; set; }
   public int Age { get; set;}
 }

//Main方法
 List list = new List() 
 { 
    new User() { Id = 1, Name = "张三", Age = 11 } ,
    new User() { Id = 1, Name = "张三", Age = 11} ,
    new User() { Id = 3, Name = "李四", Age = 13 } ,
 };
 //方法一
 list = list.GroupBy(p => p.Id).Select(q => q.First()).ToList();
 //方法二
 list = list.GroupBy(p => p.Name).Select(q => q.First()).ToList();
 //方法三
 list = list.GroupBy(p => p.Age).Select(q => q.First()).ToList();
 foreach (var item in list)
 {
   Console.WriteLine("Id:" + item.Id + ", Name:" + item.Name + ", Age:" + item.Age);
 }
 //方法四
 var list1 = (from p in list
              group p by new { p.Id, p.Name, p.Age } into g
              select g).ToList();
 foreach (var item in list1)
 {
    Console.WriteLine("Id:" + item.Key.Id + ", Name:" + item.Key.Name + ", Age:" + item.Key.Age);
 }

技术图片

C# Distinct去重泛型List

标签:class   key   group   int   sts   去重   get   write   code   

原文地址:https://www.cnblogs.com/LuckyZLi/p/11888239.html


评论


亲,登录后才可以留言!