使用LINQ从列表中获取所有相同的元素
c#
我想采用所有相同的元素,但只是从一开始,直到它发生变化。
例子:
2,2,2,2,5,6,7,8,2,3
结果:
2,2,2,2
2,2,2,2
示例 2:
结果:
5
如果没有 LINQ,这是一项非常简单的任务,但它需要的代码不止一行。而且我不知道如何使用 LINQ 轻松完成。
回答
尝试TakeWhile:
var result = input.TakeWhile(x => x == input.First());
- The `input.First()` will be executed on every enumeration, so better if you just stored it in a variable. It could be an expensive query and there's no reason to evaluate it every time.