suppose we have the list of objects
List<int> list = new List<int>() { 1,1,1,2,3,3,3,2,2,2,1,1 };
what is the most elegant way to get the following result list?
{1,2,3,2,1}
suppose we have the list of objects
List<int> list = new List<int>() { 1,1,1,2,3,3,3,2,2,2,1,1 };
what is the most elegant way to get the following result list?
{1,2,3,2,1}
I like the idea of an extension method:
public static IEnumerable<T> RemoveContiguousDuplicates<T>(this IEnumerable<T> items) where T: IEquatable<T>
{
bool init = false;
T prev = default(T);
foreach (T item in items)
{
if (!init)
init = true;
else if (prev.Equals(item))
continue;
prev = item;
yield return item;
}
}
And then, of course, to use it:
var singles = list.RemoveContiguousDuplicates().ToList();
Try this:
List<int> newList = new List<int>();
foreach (var item in list.Where(c => newList.Count == 0 || newList.Last() != c))
{
newList.Add(item); // 1,2,3,2,1 will add to newList
}