コード例 #1
0
        public void TestingSequences()
        {
            Employee p1 = new Employee()
            {
                Id = 1
            };
            Employee p2 = new Employee()
            {
                Id = 1
            };

            // Equals will return true for two objects that reference the same objects.
            Console.WriteLine("p1 equals p1 -> {0}", p1.Equals(p1));

            // It will not return true if the objects have the same values
            // but have different references (are differenct objects)
            Console.WriteLine("p1 equals p2 -> {0}", p1.Equals(p2));

            Console.WriteLine();

            var listOneP1 = new List <Employee> {
                p1
            };
            var listTwoP1 = new List <Employee> {
                p1
            };

            // SequenceEqual will return true for two sequences that reference the same objects.
            // (There is only one instance of p1)
            Console.WriteLine("listOneP1 equals listTwoP1 -> {0}", listOneP1.SequenceEqual(listTwoP1));


            var listThreeP2 = new List <Employee> {
                p2
            };

            // It will not return true if the objects have the same values but have different references
            Console.WriteLine("listOneP1 equals listThreeP2 -> {0}", listOneP1.SequenceEqual(listThreeP2));


            Console.WriteLine();
            // unless... you implement IEquatable<T> and specify which properties to compare
            Stop stop1 = new Stop {
                StopID = 1
            };

            Stop stop2 = new Stop {
                StopID = 1
            };

            var listOneStop1 = new List <Stop> {
                stop1
            };
            var listTwoStop2 = new List <Stop> {
                stop2
            };

            Console.WriteLine("listOneStop1 equals listTwoStop2 -> {0}", listOneStop1.SequenceEqual(listTwoStop2));

            Console.WriteLine();
            // fyi, constructor populates collection with some stops
            var stops1 = new Stops();
            var stops2 = new Stops();

            // this will be true because Stop implements IEquatable<T>
            Console.WriteLine("stops1 equals stops2 -> {0}", stops1.SequenceEqual(stops2));

            Console.WriteLine();

            //var s1 = "tony";
            //var s2 = "tony";

            //Console.WriteLine("s1 equals s2 -> {0}", s1.Equals(s2));
        }