score:3

Accepted answer
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.

score:1

did you try distinct?

var list = new [] { 10, 20, 20, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };
list = list.distinct();

edit: since you apparently only want to group items with the same values when consecutive, you could use the following:

var list = new[] { 10, 1, 1, 5, 25, 45, 45, 45, 40, 100, 1, 1, 2, 2, 3 };

list<int> result = new list<int>();
foreach (int item in list)
    if (result.any() == false || result.last() != item)
        result.add(item);

score:1

you can use contains and preserve order

list<int> newlist = new list<int>();

foreach (int n in numbers)
    if (newlist.count == 0 || newlist.last() != n)
       newlist.add(n);
var newarray = newlist.toarray();

output:

10, 1, 5, 25, 45, 40, 100, 1, 2, 3

score:1

it may be technically possible (though i don't think you can with a one-liner) to solve this with linq, but i think it's more elegant to write it yourself.

public static class extensionmethods
{
    public static ienumerable<t> packgroups<t>(this ienumerable<t> e)
    {
        t lastitem = default(t);
        bool first = true;
        foreach(t item in e)
        {
            if (!first && equalitycomparer<t>.default.equals(item, lastitem))
                continue;
            first = false;
            yield return item;
            lastitem = item;
        }
    }
}

you can use it like this:

int[] packed = myarray.packgroups().toarray();

it's unclear from the question what should be returned in the case of 1,1,2,3,3,1. most answers given return 1,2,3, whereas mine returns 1,2,3,1.

score:3

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);

Related Query

More Query from same tag