通过linq选择对象时的几种区别

    如果需要过滤数组,就使用Where,用Select和SelectMany主要目的是对选择进行转换。

1、Where:

测试代码:

    void TestWhere()
    {
        string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" };

        var tokens = text.Where(s => { return s.StartsWith("Bur"); });
        StringBuilder sb = new StringBuilder();
        foreach (string line in tokens)
            sb.Append(string.Format("{0}.", line));
        Debug.Log("TestWhere" + sb);
        //Burke slept late.Burning.
    }

2、SelectMany:

测试代码

    void TestSelectManay()
    {
        Debug.Log("TestSelectManay");
        string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" };
        StringBuilder sb = new StringBuilder();
        var tokens2 = text.SelectMany(s => s.Split(' '));
        foreach (string token in tokens2)
            sb.Append(string.Format("{0}.", token));
        Debug.Log("TestSelectManay" + sb);
        //输出:Albert.was.here.Burke.slept.late.Connor.is.happy.Burning.
    }

3、Select

测试代码:

    void TestSelect()
    {
        Debug.Log("TestSelect"); 
        string[] text = { "Albert was here", "Burke slept late", "Connor is happy", "Burning" }; 
        var tokens = text.Select(s => s.Split(' '));
        StringBuilder sb = new StringBuilder();
        foreach (string[] line in tokens)
            foreach (string token in line)
                sb.Append(string.Format("{0}.", token));
        Debug.Log("TestSelect" + sb);
        //输出:Albert.was.here.Burke.slept.late.Connor.is.happy.Burning.

    }

4、Select与SelectMany的区别参考这段代码:

//From stackoverflow:
//SelectMany flattens queries that return lists of lists. For example

public class PhoneNumber
{
public string Number { get; set; }
}

public class Person
{
public IEnumerable<PhoneNumber> PhoneNumbers { get; set; }
}

IEnumerable<Person> people = new List<Person>();

// Select gets a list of lists of phone numbers
IEnumerable<IEnumerable<PhoneNumber>> phoneLists = people.Select(p => p.PhoneNumbers);

// SelectMany flattens it to just a list of phone numbers.
IEnumerable<PhoneNumber> phoneNumbers = people.SelectMany(p => p.PhoneNumbers);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值