unity c# LINQ查询

LINQ数据源的基本组成部分是序列和元素。在这里,序列是指任何实现了IEnumerable<T>接口的对象,其中的每一项则称为一个元素。在下面这个示例中,names就是一个序列,而其中的Tom,Dick和Harry就是这个序列的元素:

string[] names = {"Tom","Dick","Harry"};

names表示内存中的一个对象集合,在这里我们可以称之为本地序列。

查询运算符是LINQ中用于转换序列的方法。通常,查询运算符可接收一个输入序列,并将其转换为一个输出序列。在System.Linq命名空间的Enumerable类中定义了约40种查询运算符,这些运算符都是以静态扩展方法的形式来实现的,称为标准查询运算符。

Where运算符

Where运算符是一个条件限定,它会筛选传入的序列。比如我们如果想查询names中名字长度大于等于4的,可以这样写:

var filteredNames = names.Where(n => n.Length >= 4);

完整的代码如下:

using UnityEngine;
using System.Collections;
using System.Linq;

public class LINO : MonoBehaviour {
    private string[] names = { "Tom", "Dick", "Harry" };
    public void QueryNameByLength() {
        var filteredNames = names.Where(n => n.Length >= 4);
        foreach (string name in filteredNames) {
            Debug.Log(name);
        }
    }
}

看着一句:

names.Where(n => n.Length >= 4)

Were语句中是一个Lambda表达式,这里的n表示names中的每一个元素,表达式右边的n.Length >= 4是条件。

OrderBy运算符

OrderBy表示排序的意思

如果我们想names按照名字的长度排序可以这样写

var filteredNames = names.OrderBy(n => n.Length);

完整的代码如下:

using UnityEngine;
using System.Collections;
using System.Linq;

public class LINO : MonoBehaviour {
    string[] names = { "Harry" ,"Tom", "Dick"};

    public void OrderByNameLength() {
        var filteredNames = names.OrderBy(n => n.Length);
        foreach (string name in filteredNames) {
            Debug.Log(name);
        }
    }
}


Select运算符

Select运算符的作用是将集合转换或映射成Lambda表达式中指定的形式

比如我们想把names中的字符串都变成大写的

var filteredNames = names.Select(n => n.ToUpper());


我们也可以把上面的这三种操作写在一起

var filteredNames = names.Where(n => n.Length >= 4).OrderBy(n => n.Length).Select(n => n.ToUpper());


Linq还有很多其他的函数,我们可以在相关文档中查到


上面的写法称为运算符流语法,c#还提供了另一种语法来编写LINQ语句,叫做查询表达式法

我们可以这样写Where运算符

var filteredNames = from n in names where n.Length >= 4 select n;


我们可以这样写OrderBy运算符

var filteredNames = from n in names orderby n.Length select n;

我们可以这样写Select运算符
var filteredNames = from n in names select n.ToUpper();

我们可以把它们写在一起
var filteredNames = from n in names where n.Length >= 4  orderby n.Length   select n.ToUpper();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值