• List<object>进行Distinct()去重


    有时我们会对一个list<T>集合里的数据进行去重,C#提供了一个Distinct()方法直接可以点得出来。如果list<T>中的T是个自定义对象时直接对集合Distinct是达不到去重的效果。我们需要新定义一个去重的类并继承IEqualityComparer接口重写Equals和GetHashCode方法,如下Demo

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 
     5 namespace MyTestCode
     6 {
     7     /// <summary>
     8     /// Description of DistinctDemo.
     9     /// </summary>
    10     public class DistinctDemo
    11     {
    12         private static List<Student> list;
    13         public DistinctDemo()
    14         {
    15         }
    16         
    17         public static void init()
    18         {
    19             list = new List<Student>{
    20                 new Student{
    21                     Id=1,
    22                     Name="xiaoming",
    23                     Age=22
    24                 },
    25                 new Student{
    26                     Id=2,
    27                     Name="xiaohong",
    28                     Age=23
    29                 },
    30                 new Student{
    31                     Id=2,
    32                     Name="xiaohong",
    33                     Age=23
    34                 },
    35             };
    36         }
    37         
    38         public void Display()
    39         {
    40             list = list.Distinct(new ListDistinct()).ToList();
    41             foreach (var element in list) {
    42                 Console.WriteLine(element.Id +"/"+element.Name+"/"+element.Age);
    43             }
    44         }
    45         
    46     }
    47     
    48     public class Student
    49     {
    50         public int Id{get;set;}
    51         public string Name{get;set;}
    52         public int Age{get;set;}
    53     }
    54     
    55     public class ListDistinct : IEqualityComparer<Student>
    56     {
    57         public bool Equals(Student s1,Student s2)
    58         {
    59             return (s1.Name == s2.Name);
    60         }
    61         
    62         public int GetHashCode(Student s)
    63         {
    64             return s==null?0:s.ToString().GetHashCode();
    65         }
    66     }
    67 }
  • 相关阅读:
    有个表叫杨表(上)
    Codeforces Round #698 (Div. 2) 题解 全部6题
    Leetcode 821. 字符的最短距离
    gitbook mermaid不能渲染问题
    adb命令启动app及查找系统版本号
    git库使用
    excle转html方法
    gitbook插入视频
    xcode使用技巧
    在 Mac 上的“自动操作”工作流程中使用 Shell 脚本操作
  • 原文地址:https://www.cnblogs.com/zgshi/p/7463792.html
Copyright © 2020-2023  润新知