Set Difference Minus Operation with LINQ using Except

If you have morethan two columns to compare in List Object, you need to use Equality Compare Based on Class Objects.


The following program compares two list objects and applies Set Minus operation:


protected void Page_Load(object sender, EventArgs e)
        {
            List<listclass> lst1 = new List<listclass> {  
                            new listclass { no = 1, revsion =0, title = "title1"},
                            new listclass { no = 2, revsion =0, title = "title2"},
                            new listclass { no = 3, revsion =0, title = "titleN"},
                            new listclass { no = 4, revsion =0, title = "title4"},
                         };

            List<listclass> lst2 = new List<listclass>
                            new listclass { no = 1, revsion =0, title = "title1"},
                            new listclass { no = 2, revsion =0, title = "title2"},
                            new listclass { no = 3, revsion =0, title = "title3"},
                         };

            var minus = lst1.Except(lst2, new listComparer());

            foreach (var item in minus)
            {
                Response.Write(string.Format("No:{0}, Revision:{1}, Title:{2}", item.no, item.revsion, item.title));
            }   
        }
 
        public class listclass
        {
            public int no {get; set;}
            public int revsion {get; set;}
            public string title { get; set; }
        }

        public class listComparer : EqualityComparer<listclass>
        {
            public override bool Equals(listclass x, listclass y)
            {
                if (ReferenceEquals(x,y)) return true;

                return x.no == y.no && 
                       x.revsion == y.revsion && 
                       x.title == y.title;
            }

            public override int GetHashCode(listclass obj)
            {
                if (ReferenceEquals(obj, null)) return 0;
                {
                    var noHash = obj.no == null ? 0 : obj.no.GetHashCode();


            var revsionHash = obj.revsion == null ? 0 : obj.revsion.GetHashCode();


        var titleHash = obj.title == null ? 0 :   obj.title.GetHashCode();

                    return noHash ^ revsionHash ^ titleHash;
                }
            }
        }


Output:
      No:3, Revision: 0, Title: titleN
      No:4, Revision: 0, Title: title4

Ref: http://christopherdeweese.com/blog2/post/loving-linq-generics-using-except-with-equalitycomparert

Comments

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

How to get Client's Location using IPAddress