加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#Linq列表需要一段时间

发布时间:2020-12-16 10:41:21 所属栏目:百科 来源:网络整理
导读:请查看 Linqpad中的以下代码,并告诉我为什么它返回0项而不是1项. void Main(){ string[] strArray = {"apple","banana","cherry","e"}; Liststring lst = strArray.ToList(); //count all occurences of variable alphabet "e" in LINQ //tip is to get the
请查看 Linqpad中的以下代码,并告诉我为什么它返回0项而不是1项.

void Main()
{
    string[] strArray = {"apple","banana","cherry","e"};
    List<string> lst = strArray.ToList();

    //count all occurences of variable alphabet "e" in LINQ

    //tip is to get the occurences of letter "e" in each word
    // and then total them together

    var lst2 = lst.TakeWhile(c=>c.Equals("banana")).Select(c=>c);

    Console.WriteLine(lst2);
}

上面的代码没有像我期望的那样在linqpad中返回1个项目.相反,它返回0项.带有1个项目“banana”的列表应该返回.为什么不呢?

解决方法

只要条件为真,TakeWhile将采用元素.在你的情况下,它在开始时是假的,因为它评估是否(“apple”==“banana”)并且不是TakeWhile停止.

如果你把元素“banana”放在开头,它就会起作用.

string[] strArray = {"banana","apple","e"};

另外,你只能写.

var lst2 = lst.TakeWhile(c=>c.Equals("banana"))

选择没用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读