0

I'll take it directly: For example I have an array

int[] integers = {1, 2, 2, 2, 4, 5, 2, 2, 2};

And all I like is to reduce all the stacks of 2 into only one 2. I need to get this at the end:

{1, 2, 4, 5, 2};

I read about the .Distinct() method and every kind of comparers, but that method deletes all the same elements and I don't want this. I still think there shold be some certain method to do it via Linq or somethig. Thanks!

D. Petrov
  • 1,147
  • 15
  • 27
  • Check this out http://stackoverflow.com/questions/3350641/array-remove-duplicate-elements – Full Stack Developer - Java Apr 27 '16 at 15:15
  • If I understand you, what you want is something that does the same thing as [the Unix ``uniq`` utility](http://linux.die.net/man/1/uniq), except that it acts on the entries of an array rather than on the lines of a file. – David K Apr 27 '16 at 16:09
  • What language are you using? There seem to be "unique" functions in many languages, but they eliminate _all_ duplicates, not just consecutive ones. Here is what someone had to do to work around this in Ruby, for example: http://stackoverflow.com/questions/4576652/how-do-you-merge-consecutive-repeating-elements-in-an-array – David K Apr 27 '16 at 16:16
  • @David K thanks, I'm gonna check that Ruby out, I think I'm gonna be ok with that. Gonna post a refference as soon as I'm done. – D. Petrov Apr 28 '16 at 05:49

2 Answers2

1

Use the LINQ, Luke!

var result = integers.Where((n, i) =>
    i == 0 ? true : n != integers[i - 1]);

More concise:

var result = integers.Where((n, i) =>
    i == 0 || n != integers[i - 1]);
Alexander Petrov
  • 13,457
  • 2
  • 20
  • 49
0

I think .net doesn't have function for this.

So you should use simple foreach.

var result = List<int>();
foreach(var item in integers)
{
    if(!result.Any())
    {
        result.Add(item);
    }
    else if(result[result.Count() - 1] != item)
    {
        result.Add(item);
    }
}
Mediator
  • 14,951
  • 35
  • 113
  • 191