C ා notes -- the application of object-oriented basic set in OOP

Posted by flashmonkey on Mon, 27 Jan 2020 09:40:31 +0100

(1) Generic collection List

1) Introduction

Limitations of arrays:
  • The number of array elements is fixed. Once an array is defined, the total number of elements cannot be changed. If the requirements change, the source code must be modified;
  • If the total number of initialization elements is very large, space will be wasted;
Characteristics of set:
  • Dynamically increase the number of elements according to the needs without limitation;

2) Generic set

1. Features of list generic set:
  • Represents a generic Type, T is a shorthand for Type, indicating that the specific Type is not determined at present;
  • According to the actual needs of users, the data type of the current set can be determined; however, once it is determined, it cannot be changed;
2. Storage structure of list generic collection:

3. Requirements for generic sets:
  • Only one type of data can be added by using generic sets, and there is no need to cast data after fetching;
4. Preparations before using the list:
  • Introduce namespace: System.Collections.Generic;
  • Determine storage type:
List<Student> students = new List<Student>();
5. Common methods:
  • Add element: add (< T >)
  • Remove element: removeat (index)
6. Common attributes:

Number of elements: Count

7. Traversal set:
foreach (Student stu in students)
{
	Console.WriteLine(stu.StudentName);
}
Give an example:
namespace Demo
{
    /// <summary>
    //Student class
    /// </summary>
    class Student
    {
        public Student() { }
        public Student(int stuId, string stuName)
        {
            this.StudentId = stuId;
            this.StudentName = stuName;
        }
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public int Age { get; set; }
    }
}
using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create student object
            Student objStu1 = new Student(1001, "Xiao Wang");
            Student objStu2 = new Student(1002, "Xiao Zhang");
            Student objStu3 = new Student(1003, "petty thief");
            Student objStu4 = new Student(1004, "Xiao Zhao");

            //Create list collection
            List<Student> StuList = new List<Student>();
            StuList.Add(objStu1);
            StuList.Add(objStu2);
            StuList.Add(objStu3);
            StuList.Add(objStu4);
            StuList.Add(new Student()
            {
                StudentId = 1006,
                StudentName = "Small black"
            });

            //Get the number of elements
            Console.WriteLine("Total elements:{0}", StuList.Count);

            //Delete an element
            StuList.Remove(objStu1);        //Delete an object
            StuList.RemoveAt(1);            //Delete element at position 1

            //Insert an object
            StuList.Insert(0, new Student(1005, "Xiao Bai"));

            //Ergodic set
            foreach (Student item in StuList)
            {
                Console.WriteLine(item.StudentName + "\t" + item.StudentId);
            }
            
        }
    }
}

8. Set initializer:

When creating a collection object, it is initialized directly, very similar to an array;

(2) The use of generic set dictionary < K, V >

1) On dictionary < K, V > generic sets

  • Dictionary < K, V > is usually called dictionary, and element types in < K, V > constraint set;
  • During compilation, type constraints are checked without packing and unboxing, similar to hash table operations;
Storage structure of dictionary < K, V >

Give an example:
namespace Demo
{
    /// <summary>
    //Student class
    /// </summary>
    class Student
    {
        public Student() { }
        public Student(int stuId, string stuName)
        {
            this.StudentId = stuId;
            this.StudentName = stuName;
        }
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public int Age { get; set; }
    }
}
using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create student object
            Student objStu1 = new Student(1001, "Xiao Wang");
            Student objStu2 = new Student(1002, "Xiao Zhang");
            Student objStu3 = new Student(1003, "petty thief");
            Student objStu4 = new Student(1004, "Xiao Zhao");

            //Create a Dictionary generic collection
            Dictionary<string, Student> stus = new Dictionary<string, Student>();
            stus.Add("Xiao Wang", objStu1);
            stus.Add("Xiao Zhang", objStu2);

            //Note that brackets are used here
            Console.WriteLine(stus["Xiao Wang"].StudentId);

            //Dictionary generic set traversal (two ways)
            //First kind
            foreach (string key in stus.Keys)
            {
                Console.WriteLine(key);
            }

            //Second kinds
            foreach (Student item in stus.Values)
            {
                Console.WriteLine(item.StudentName + "\t" + item.StudentId);
            }
        }
    }
}

(3) Sorting of objects in a collection

1) Sorting of basic data types

The basic data types can be sorted directly; with the Sort() method, string elements are sorted in ascending alphabetical and Pinyin order by default;

Note: use the Reverse() method to implement inversion;
List<string> list = new List<string>()
            {
                "Xiao Wang","Xiao Zhang","Little grandson","petty thief","Xiao Zhao"
            };
            foreach (string item in list)
            {
                Console.WriteLine(item);
            }


            Console.WriteLine("--------After sorting--------");

            list.Sort();            //sort
            list.Reverse();         //Reverse after sorting
            foreach(string item in list)
            {
                Console.WriteLine(item);
            }

2) Sorting of objects

Set can't be sorted simply by Sort();
Reason: cannot find sorting attribute;

Note: a class is preceded by "I" to indicate the interface of this class;

Implement the generic interface IComparable < T > to sort objects by student number

Note: return this.StuId.CompareTo(other.StuId) implements ascending sorting (by student number)
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;

namespace Demo
{
    /// <summary>
    //Student class
    /// </summary>
    class Student:IComparable<Student>
    {
        public Student() {}
        public Student(int stuId, string stuName)
        {
            this.StudentId = stuId;
            this.StudentName = stuName;
        }
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public int Age { get; set; }
        
        /// <summary>
        ///Implementation of interface
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int CompareTo([AllowNull] Student other)
        {
            //The following code implements ascending sort; the exchange location of this and other implements descending sort
            return this.StudentId.CompareTo(other.StudentId);
        }
    }
}

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student objStu1 = new Student(1001, "Xiao Wang");
            Student objStu2 = new Student(1002, "Xiao Zhang");
            Student objStu3 = new Student(1003, "Xiao Zhao");
            Student objStu4 = new Student(1004, "Little grandson ");
            List<Student> Stus = new List<Student>() { objStu1, objStu2, objStu3, objStu4 };

            Stus.Sort();

            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentName);
            }

        }
    }
}

3) Object sorting ------ add sorting method (dynamic) as required

There can only be one default sort
The interface itself is a data type, and the class is a data type;

Be careful:
  • There can only be one default sort;
  • Add sorting classes as needed. In C, a class file is allowed to correspond to several specific classes;
  • Add several sorting classes if you need several sorts;
  • When multiple sorts are needed, the default sort can be avoided; the following sort can completely replace the default sort;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;

namespace Demo
{
    /// <summary>
    //Student class
    /// </summary>
    class Student:IComparable<Student> //There can only be one default sort
    {
        public Student() {}
        public Student(int stuId, string stuName)
        {
            this.StudentId = stuId;
            this.StudentName = stuName;
        }
        public int StudentId { get; set; }
        public string StudentName { get; set; }

        public int Age { get; set; }
        
        /// <summary>
        ///Implementation of interface
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int CompareTo([AllowNull] Student other)
        {
            //The following code implements ascending sort; the exchange location of this and other implements descending sort
            return this.StudentId.CompareTo(other.StudentId);
        }
    }

    //Add sorting classes as needed. In C, a class file is allowed to correspond to several specific classes
    //Add several sorting classes if you need several sorts
    //Add sorting class and implement sorting interface respectively
    class StuNameASC : IComparer<Student>       //Implement this interface
    {
        public int Compare([AllowNull] Student x, [AllowNull] Student y)
        {
            return x.StudentName.CompareTo(y.StudentName);
        }
    }
    class StuNameDESC : IComparer<Student>
    {
        public int Compare([AllowNull] Student x, [AllowNull] Student y)
        {
            return y.StudentName.CompareTo(x.StudentName);
        }
    }
    class AgeASC : IComparer<Student>
    {
        public int Compare([AllowNull] Student x, [AllowNull] Student y)
        {
            return x.Age.CompareTo(y.Age);
        }
    }

    class AgeDESC : IComparer<Student>
    {
        public int Compare([AllowNull] Student x, [AllowNull] Student y)
        {
            return y.Age.CompareTo(x.Age);
        }
    }
}

using System;
using System.Collections.Generic;

namespace Demo
{
    class Program
    {

        static void Main(string[] args)
        {
            Student objStu1 = new Student() { StudentId = 1001, StudentName = "petty thief", Age = 20 };
            Student objStu2 = new Student() { StudentId = 1002, StudentName = "Zhang Hong", Age = 27 };
            Student objStu3 = new Student() { StudentId = 1003, StudentName = "Wang Yang", Age = 22 };
            Student objStu4 = new Student() { StudentId = 1004, StudentName = "Hao Xin", Age = 17 };
            List<Student> Stus = new List<Student>() { objStu1, objStu2, objStu3, objStu4 };
            
            //Default sort
            Stus.Sort();
            Console.WriteLine("-------Default sort--------");
            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t"+ item.Age);
            }
            Console.WriteLine("-------Ascending by name-------");
            Stus.Sort(new StuNameASC());        //It must be the object of the interface implementation class
            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
            }
            Console.WriteLine("-------Descending by name-------");
            Stus.Sort(new StuNameDESC());
            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
            }
            Console.WriteLine("-------In ascending order of age-------");
            Stus.Sort(new AgeASC());
            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
            }
            Console.WriteLine("-------In descending order of age-------");
            Stus.Sort(new AgeDESC());
            foreach (Student item in Stus)
            {
                Console.WriteLine(item.StudentId + "\t" + item.StudentName + "\t" + item.Age);
            }

        }
    }
}
In fact, the above is an application of polymorphism; polymorphism can be realized in two ways
  1. Based on inheritance; (1) taking the parent class as the parameter of the method, what is actually passed is the child object of the parent class; (2) taking the parent class type as the return value of the method;
  2. Based on the interface; (1) taking the interface as the parameter of the method, passing in the implementation class object of the interface; (2) taking the interface as the return value;

4) Sort method summary

There are four Sort methods for the List set:
  1. Sort(): use the default comparator IComparable < > to sort objects; [no parameters]
  2. Sort (Icompare < > compare): takes the object that implements the comparer interface as a parameter; [typical polymorphism]
    ...
Collection sort summary:
  • If it is a basic data type element, it can be sorted directly;
  • If it is an object type element:
    1. When there is only one sort, you can use the default comparer IComparable < > to implement the interface in the class;
    2. When multiple sorts are needed, corresponding sort classes need to be added, and the comparer interface Icompare < > is implemented for each sort class to complete different sort methods;
32 original articles published, praised 0, 919 visitors
Private letter follow

Topics: Attribute