[U3D Learning Note] Unity C# Survival Guide (18) -- LINQ

tech2022-08-10  155

LINQ: Queries

LINQ: language intergrated query. allow us filter through data, especially filter through arrays and lists.

Any: search wheather there is the target we want. before learning Linq, we usually use foreach loop to match a target in array or list. But by using Linq, we can use keyword any to do the same thing. 在下面这个代码中, 参数是输入为string类型返回为bool类型的Func(Func是一种特殊的delegate哦,上一节讲过的)。IEnumerable是枚举器,实现了foreach的功能,即对于每一个string类型的信息执行括号内方法并返回bool值。 public string[] names = {"camus", "mizuki", "masa", "ren", "ren"}; // Start is called before the first frame update void Start() { //pass in a string and do some condition checking and then going to return a bool var nameFound = names.Any(name => name=="masa"); } Contains: check if sth. were to exist. (simple ver of any 区别是any是查找是否有满足某条件的, 而Contains是查找目标是否存在于数组中) var nameFound = names.Contains("masa"); Distinct: remove all duplicate elements in a collection and return only distinct or unique elements. var newNames = names.Distinct();

注意:Distinct的作用是移除重复的元素并生成新的集合来装处理过的数据。原数组的元素并不会被删除。

Where: allow us to sort an existing collection, and create a new collection based on some condition. var selectNames = names.Where(n => n.Length>5);

Order by Descending

OrderByDescending(): 降序排列 var desName = names.OrderByDescending(g => g); Reverse(): 翻转

How to Read and Convert Query Syntax

第一种是query syntax, 看上去很像mysql语句啊, 第二种就是我们前面说的linq,也就是method syntax,两种实现的功能是一样的

int[] scores = new int[] { 97, 92, 81, 60 }; // Start is called before the first frame update void Start() { // Define the query expression.(query syntax) IEnumerable<int> scoreQuerySyntax = from score in scores where score > 80 select score; // method syntax var scoreQuery = scores.Where(score => score>80); }
最新回复(0)