首页 > 其他 > 详细

对象集合去重问题?

时间:2016-03-23 17:16:39      阅读:332      评论:0      收藏:0      [点我收藏+]
 1         //方法1
 2         public class Data:IEquatable<Data>
 3         {
 4             public string Email { get; set; }
 5             public string Remark { get; set; }
 6 
 7             public bool Equals( Data other)
 8             {
 9                 return this.Email == other.Email;//根据某个或多个字段去重
10             }
11             public override int GetHashCode()
12             {
13                 return Email.GetHashCode();
14             }
15         }
16         //方法2
17         public class UserComparer : IEqualityComparer<Data>
18         {
19             public bool Equals(Data x, Data y)
20             {
21                 if (x == null && y == null)
22                 {
23                     return false;
24                 }
25                 return x.Email.ToUpper() == y.Email.ToUpper();
26             }
27             public int GetHashCode(Data obj)
28             {
29                 return obj.ToString().GetHashCode();
30             }
31         }
32 
33             List<Data> list = new List<Data>();
34             list.Add(new Data { Email = "123", Remark = "345" });
35             list.Add(new Data { Email = "abc", Remark = "456" });
36             list.Add(new Data { Email = "abc", Remark = "456" });
37             list.Add(new Data { Email = "abc", Remark = "789" });
38 
39             //方法1
40             List<Data> ll = list.Distinct().ToList();
41 
42             //方法2
43             List<Data> l2 = list.Distinct(new UserComparer()).ToList();
44 
45             //方法3
46             List<Data> l3 = list.Where((x, i) => list.FindIndex(z => z.Email == x.Email) == i).ToList();
            //去重完全相同的对象

            //方法1
            var list1 = list.Select(a => new { Email = a.Email, ReMark = a.Remark }).Distinct();
            //方法2
            var list2 = (from q in list
                         select new
                         {
                             Email = q.Email,
                             Remark = q.Remark
                         }).Distinct();

 

 

对象集合去重问题?

原文:http://www.cnblogs.com/xiaohui1990/p/5311681.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!