using System.Collections.Generic;
public static void Main()
List<int> myList1 = null;
List<int> myList2 = new() { };
List<int> myList3 = new() { 1 };
List<int> myList4 = new() { 1, 1 };
List<int> myList5 = new() { 1, 2 };
List<int> myList6 = new() { 1, 2, 1 };
List<int> myList7 = new() { 1, 1, 2, 1 };
List<int> myList8 = new() { 1, 2, 1, 1 };
List<int> myList9 = new() { 1, 1, 9, 2, 2, 3, 9, 4, 5, 5, 1, 9, 9 };
List<List<int>> lists = new() { myList1, myList2, myList3, myList4, myList5, myList6, myList7, myList8, myList9 };
foreach (var list in lists)
var filteredList = GetFilteredList(list);
Console.WriteLine("Original list: " + (list == null ? "null" : "{ " + string.Join(", ", list) + " }"));
Console.WriteLine("Filtered list: " + (filteredList == null ? "null" : "{ " + string.Join(", ", filteredList) + " }"));
public static List<int> GetFilteredList(List<int> list)
var filtered = list.AsEnumerable();
if (list.First() == list.Skip(1).First())
filtered = filtered.SkipWhile(l => l == list.First());
if (list.Last() == list.SkipLast(1).Last())
filtered = filtered.SkipLastWhile(l => l == list.Last());
return filtered.ToList();
public static class Helper
public static IEnumerable<TSource> SkipLastWhile<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
var buffer = new List<TSource>();
foreach (var item in source)
foreach (var bufferedItem in buffer)
yield return bufferedItem;