[100 Unity Practical Skills] Detailed explanation of List.Find method in C# Find the first element that meets the requirements and return

Hits: 0

Unity small science

Old rules, first introduce the popular science knowledge of Unity :

  • Unity is a real-time 3D interactive content creation and operation platform.
  • All creators, including game development , art , architecture , automotive design , film and television , turn their ideas into reality with Unity .
  • The Unity platform provides a complete set of software solutions for creating, operating and monetizing any real-time interactive 2D and 3D content, supporting platforms including mobile phones , tablets , PCs , game consoles , augmented reality and virtual reality devices.
  • Unity can also be simply understood as a game engine , which can be used to make games professionally !

Unity practical skills learning

Detailed explanation of List.Find method in C# Find the first element that meets the requirements and return

A previous article introduced that List is Existsused to determine whether the object exists and return a boolean value.

This article is similar, but instead of boolean values, concrete objects are returned.

public T Find(Predicate<T> match);

The storage type determined by the user when the generic T is defined for the list, the Predicate match is a delegate, which can be understood as a function pointer.

The specific usage is as follows:

base type

// base type 
        List <int> list1 = new  List <int>() { 11 , 12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 };

        var l = list1.Find(t => t == 15);
        Debug.Log( "Returned value: " +l);

reference type

//reference type 
    public  class  User
    {
        public string Name;
        public int Age;
    }
    void  UserTest ()
    {
        //Reference type 
        List<User> list1 = new List<User>() {
             new User { Name = "Little Y" , Age = 20 },
             new User { Name = "Little Y" , Age = 22 },
               new User { Name = "Little Y" , Age = 12 }
        };

        Debug.Log("Age:" + l.Age);
    }

The returned results are as follows:

important point:

  • The value returned by Find, if found, will return the value of the found object in the List, if not found, it will return the default value of the object.
  • When the object is a reference type , the value of the object is the memory address pointing to the object, and the returned value can be used to directly modify the elements in the list. At this time, the default value of the object is null.
  • If the object is a value type , the value of the object is the object itself, and the return value returns a copy of the object. Modifications to the returned object cannot affect the elements in the list.

Leave a Reply

Your email address will not be published.