Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group the same values in a sequence with LINQ?

Tags:

c#

.net

linq

I have a sequence. For example:

new [] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 }

Now I have to remove duplicated values without changing the overall order. For the sequence above:

new [] { 10, 1, 5, 25, 45, 40, 100, 1, 2, 3 }

How to do this with LINQ?

like image 821
alexey Avatar asked Jan 16 '23 13:01

alexey


2 Answers

var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
        List<int> result = list.Where((x, index) =>
        {
            return index == 0 || x != list.ElementAt(index - 1) ? true : false;
        }).ToList();

This returns what you want. Hope it helped.

like image 195
Dovydas Navickas Avatar answered Jan 31 '23 02:01

Dovydas Navickas


var list = new List<int> { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };

var result = list.Where((item, index) => index == 0 || list[index - 1] != item);
like image 44
Helstein Avatar answered Jan 31 '23 00:01

Helstein