求2个集合的差集

        /// <summary>
        /// 求2个集合的差集
        /// </summary>
        public class wage
        {
            public static void Test()
            {
                List<wage> list1 = new List<wage>
                                       {
                                           new wage { Id = 1, Name = "list1" },
                                           new wage { Id = 2, Name = "list1" },
                                           new wage { Id = 3, Name = "list1" },
                                           new wage { Id = 5, Name = "list1" },
                                           new wage { Id = 6, Name = "list1" }
                                       };
                List<wage> list2 = new List<wage>
                                       {
                                           new wage { Id = 1, Name = "list2", },
                                           new wage { Id = 2, Name = "list2", },
                                           new wage { Id = 3, Name = "list2", },
                                           new wage { Id = 4, Name = "list2", },
                                           new wage { Id = 5, Name = "list2", }
                                       };

                ////var union = list1.Union(list2, new MyComparer()).ToList();
                ////var intersect = list1.Intersect(list2, new MyComparer()).ToList();
                ////var except = union.Except(intersect, new MyComparer()).ToList();

                var result = list1.Union(list2, new MyComparer()).Except(list1.Intersect(list2, new MyComparer()), new MyComparer());
                foreach (var item in result)
                {
                    Console.WriteLine("id = {0},  name = {1}", item.Id, item.Name);
                }
            }

            public int Id { set; get; }

            public string Name { set; get; }

            public class MyComparer : IEqualityComparer<wage>
            {
                public bool Equals(wage x, wage y)
                {
                    return x.Id == y.Id;
                }

                public int GetHashCode(wage obj)
                {
                    return obj.Id;
                }
            }
        }

 

posted @ 2015-06-16 11:27  刘小吉  阅读(838)  评论(0编辑  收藏  举报