The use of List, Array and the use of Sort method

List

Create a new List
 		List<int> _list_int_0 = new List<int>();
        for (int i = 0; i < 5; i++)
        {
    
    
            _list_int_0.Add(i * 100 + 100);
        }

        foreach (var item in _list_int_0)
        {
    
    
            Debug.Log(item);
        }
        // Log 100,200,300,400,500
List .AddRange

List .AddRange() method is used to add objects/elements of the specified collection to the end of the list.

		 int[] _int_arr_0 = {
    
     400, 500, 600 };
        _list_int_0.AddRange(_int_arr_0);

        List<int> _list_int_1 = new List<int>();
        _list_int_1.Add(50);
        _list_int_1.Add(60);
        _list_int_1.Add(70);
        _list_int_0.AddRange(_list_int_1);

        foreach (var item in _list_int_0)
        {
    
    
            Debug.Log(item);
        }
    }

Output elements
Insert image description here

List.InsertRange(index, colliection)

Insert the specified object collision starting from index

List.ConvertAll

Convert the elements in the list to the desired type

		List<string> _list_str_0 = _list_int_0.ConvertAll(t => Convert.ToString(t));

        foreach (var data in _list_str_0)
        {
    
    
            Debug.Log(data);
        }

Output elements
Insert image description here

List.Reverse

flip all elements

List.RemoveRange(index, count)

Remove count number of elements starting from index position

Array

The Array class provides various properties and methods for arrays, which can be regarded as an array with expanded functions but not the same as an array.

  1. Create a new 3D array
	void creatList3()
    {
    
    
        int x = 2;
        int y = 3;
        int z = 4;

        int[,,] arr3 = new int[x, y, z];
        for (int i = 0; i < x; i++)
        {
    
    
            for (int j = 0; j < y; j++)
            {
    
    
                for (int k = 0; k < z; k++)
                {
    
    
                    arr3[i, j, k] = i * j * k;
                    string str = string.Format("{0}-{1}-{2}:\t", i, j, k) + "<color=#00FF2E>" + arr3[i, j, k].ToString() + "</color>";
                    creatTxtMesh(str, new Vector3(i * 20, j * 10, k *10));
                }
            }
        }
    }

    void creatTxtMesh(string str, Vector3 pos)
    {
    
    
        TextMeshPro text = new GameObject().AddComponent<TextMeshPro>();
        text.text = str;
        text.alignment = TextAlignmentOptions.Center;
        text.transform.position = pos;
    }

The array is as follows:
Insert image description here
2. Rank
gets the dimensions of the array

		for (int i = 0; i < arr3.Rank; i++)
        {
    
    
            Debug.Log("GetUpperBound" + arr3.GetUpperBound(i));
            Debug.Log("GetLowerBound" + arr3.GetLowerBound(i));
        }

Insert image description here

  1. GetUpperBound(index)

    Get the index of the last element of the specified dimension in Array

  2. GetUpperBound(index)
    gets the index of the first element of the Array specified dimension

  3. Array.Clear(array, index, length)
    sets the range of elements in array (starting at index and length) to 0, false or null according to the element type

  4. GetLength(dimension)/GetLongLength(dimension)
    obtains a 32/64-bit integer representing the number of elements in the specified dimension of Array.

	Debug.Log("Length:  " + arr3.GetLength(0));

Sort method

Sort method without parameters

Directly using this method cannot sort any element object in the List., The element objects in the List must inherit the IComparable interface, and implement the CompareTo() method in the IComparable interface . In the CompareTo() method, you must implement the comparison rules of the objects yourself.
For example, Int32 and Double are structures that implement the IComparable interface and overload the CompareTo method.

  1. Sort Int
 	void sortInt()
    {
    
    
        List<int> arr = new List<int>();
        for (int i = 0; i < 10; i++)
        {
    
    
            arr.Add(UnityEngine.Random.Range(0, 10));
        }

        string str = "";
        foreach (var item in arr)
        {
    
    
            str += (item + "-");
        }
        Debug.Log("str: " + str);
        arr.Sort();
        str = "";
        foreach (var item in arr)
        {
    
    
            str += (item + "-");
        }
        Debug.Log("sort: " + str);
    }

The output is as follows

Insert image description here
For types that do not officially implement the IComparable interface, you can sort by implementing the IComparable interface and overriding the CompareTo method.

Implement the IComparable interface and override CompareTo

Single weight sorting
Create new parameter type

using System;

public class Props : IComparable<Props>
{
    
    
    public int id;
    public int quality;
    public int count;

    // 重写Compare方法
    public int CompareTo(Props props)
    {
    
    
        // 默认根据品质排序
        if (quality > props.quality)
            return -1;
        else
            return 1;
    }

    public Props()
    {
    
    
        id = 0;
        quality = 0;
        count = 0;
    }

    public Props(int _id, int qua, int cou)
    {
    
    
        id = _id;
        quality = qua;
        count = cou;
    }
}

Sort

void initProps()
    {
    
    
        List<Props> props = new List<Props>();
        for (int i = 0; i < 10; i++)
        {
    
    
            Props item = new Props();
            item.id = i;
            item.quality = i / 3;
            item.count = (i > 7) ? 7 : i;
            props.Add(item);
        }
        Debug.Log("排序前");
        foreach (var item in props)
        {
    
    
            Debug.Log(string.Format("id: {0} \t quality: {1} \t count: {2}", item.id, item.quality, item.count));
        }
        props.Sort();
        Debug.Log("排序后");
        foreach (var item in props)
        {
    
    
            Debug.Log(string.Format("id: {0} \t quality: {1} \t count: {2}", item.id, item.quality, item.count));
        }
    }

The output is as follows
Insert image description here
Insert image description here

Multiple weight sorting
Add a multi-weight sorting method to the parameter class

	// 多权重排序
    public int CompareQua2Cou(Props a, Props b)
    {
    
    
        if (a.quality > b.quality)
            return -1;
        else if (a.quality == b.quality)
        {
    
    
            // 同品质按数量排序
            // a.count.CompareTo(b.count) * -1
            return -a.count.CompareTo(b.count);
        }
        else
            return 1;
    }

Sort

		props.Sort((a, b) => a.CompareQua2Cou(a,b));
        Debug.Log("排序后");
        foreach (var item in props)
        {
    
    
            Debug.Log(string.Format("id: {0} \t quality: {1} \t count: {2}", item.id, item.quality, item.count));
        }

Sort results
Insert image description here

Use anonymous functions to implement Comparison

Single weight sorting

		props.Sort((a, b) =>
        {
    
    
            return b.count - a.count;
        });
        Debug.Log("排序后");
        foreach (var item in props)
        {
    
    
            Debug.Log(string.Format("id: {0} \t quality: {1} \t count: {2}", item.id, item.quality, item.count));
        }

Output results

Insert image description here
Multiple weight sorting

 		props.Sort((a, b) =>
        {
    
    
            if (a.quality > b.quality)
            {
    
    
                return 1;
            }else if (a.quality == b.quality)
            {
    
    
                return a.count - b.count;
            }
            else
            {
    
    
                return -1;
            }
        });
        // 另一种写法
        //props.Sort((a, b) =>
        //{
    
    
        //    return a.quality.CompareTo(-b.count);
        //});

result
Insert image description here

Guess you like

Origin blog.csdn.net/the_vnas/article/details/130522475