码迷,mamicode.com
首页 > 其他好文 > 详细

Linq的TakeWhile的用法

时间:2020-03-23 18:57:11      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:com   contain   can   count   color   return   lang   tar   osi   

http://www.codewars.com/kata/56676e8fabd2d1ff3000000c/train/csharp

Can you find the needle in the haystack?

Write a function findNeedle() that takes an array full of junk but containing one ‘needle‘

After your function finds the needle it should return a message (as a string) that says:

‘found the needle at position ‘ plus the index it found the needle

So

findNeedle([‘hay‘, ‘junk‘, ‘hay‘, ‘hay‘, ‘moreJunk‘, ‘needle‘, ‘randomJunk‘])

should return

‘found the needle at position 5‘

 

 public static string FindNeedle(object[] haystack)
        {
            const string needle = "needle";
            var strings = haystack.Select(x => x.ToString());
            int position = strings.TakeWhile(str => !str.Equals(needle)).Count();
            return $"found the needle at position {position}";
        }

 

Linq的TakeWhile的用法

标签:com   contain   can   count   color   return   lang   tar   osi   

原文地址:https://www.cnblogs.com/chucklu/p/5084696.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!