一、常用方式
1、排序
(1)简单排序:
//调用sort方法,如果需要降序,进行反转:
List<int> list = new List<int>();
list.Sort();// 升序排序
list.Reverse();// 反转顺序
(2)使用lambda表达式排序
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
struct IntStruct
{
public int index;
public int num;
public string name;
public IntStruct(int index, int num, string name)
{
this.index = index;
this.num = num;
this.name = name;
}
}
public class ListTest : MonoBehaviour
{
List<IntStruct> intStructs = new List<IntStruct>();
void Start()
{
Init();
Debug.Log("排序前:");
PrintList();
//intStructs.Sort((x, y) => -x.index.CompareTo(y.index));//方法1
//intStructs = intStructs.OrderBy(o => o.index).ToList();//升序 //方法2:需要引入System.Linq命名空间
intStructs = intStructs.OrderBy(o => o.index).ThenBy(o => o.num).ToList();//多重排序 使用ThenByDescending则降序
Debug.Log("排序后:");
PrintList();
}
private void Init()
{
IntStruct one = new IntStruct(1, 101, "小米");
IntStruct two = new IntStruct(2, 102, "华为");
IntStruct three = new IntStruct(3, 1032, "荣耀");
IntStruct four = new IntStruct(3, 1031, "使命");
intStructs.Add(one);
intStructs.Add(two);
intStructs.Add(three);
intStructs.Add(four);
}
private void PrintList()
{
for (int i = 0; i < intStructs.Count; i++)
{
Debug.Log(intStructs[i].name);
}
}
}
1663127584504.png
2、查找
(1) 简单查找,直接用Find或者Contains
(2) 使用lambda表达式
1663129003877.png
二、使用注意点:
1、凡是集合,在遍历的时候不要去删除集合中的元素,以及更改元素的索引顺序。












网友评论