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

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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值