Thursday, May 19, 2011

Compare data in List<> (Compare two Lists)

List<>.SequenceEqual() can be used to compare data in two sequences.

if you are going to store instances of your own classes, you will need to implement IEquatable and IComparable interfaces in the classes.

        class MyClass : IEquatable, IComparable
        {
            public string text { get; set; }
            public int number { get; set; }

            #region IEquatable<> methods
            public override bool Equals(object other)
            {
                return base.Equals(other as MyClass);
            }

            public bool Equals(MyClass other)
            {
                return (text == other.text) && (number == other.number);
            }

            public override int GetHashCode()
            {
                return text.GetHashCode() ^ number.GetHashCode();
            }
            #endregion

            public int CompareTo(MyClass other)
            {
                int a = this.GetHashCode();
                int b = other.GetHashCode();
                return a.CompareTo(b);
            }
        }

Now you can use SequenceEqual():

        list1.Sort();
        list2.Sort();

        list1.SequenceEqual(list2)


example:


            List list1 = new List()
                {
                    new MyClass(){ text = "text22", number = 2},
                    new MyClass(){ text = "text11", number = 1}
                };

            List list2 = new List()
                {
                    new MyClass(){ text = "text11", number = 1},
                    new MyClass(){ text = "text22", number = 2}
                };

            list1.Sort();
            list2.Sort();

            if (list1.SequenceEqual(list2))
            {
                Console.WriteLine("equal");
            }

No comments:

Post a Comment