user15515307
user15515307

Reputation:

Take all the same elements from list with LINQ

I want to take all elements which are the same, but only from the start, until it changes.

Example:

2,2,2,2,5,6,7,8,2,3

Result:

2,2,2,2

Example 2:

5,6,7

Result:

5

It's incredibly easy task to do without LINQ, but it will take more than one line of code. And I can't figure it out how to do it easily with LINQ.

Upvotes: 1

Views: 101

Answers (2)

SomeBody
SomeBody

Reputation: 8743

Try TakeWhile:

var result = input.TakeWhile(x => x == input.First());

Upvotes: 5

tmaj
tmaj

Reputation: 34967

Here's my attempt:

var a = new[]{2,2,2,2,5,6,7,8,2,3};

var start = a.TakeWhile(i => i == a[0]);

Console.WriteLine(string.Join(",", start)); // 2,2,2,2

Upvotes: 1

Related Questions