Home > database >  C# linq remove duplicates from the top and bottom of the list and keep the duplicates in the middle
C# linq remove duplicates from the top and bottom of the list and keep the duplicates in the middle

Time:05-15

C# linq remove duplicates from the top and bottom of the list and keep the duplicates in the middle For example,

  var myArray = new[] { 1, 1, 2, 2, 3,4,5,5,9,9 };
  List<int> myList = myArray.ToList();

Expected Output after removing the duplicates at the top and bottom is below list

{ 2, 2, 3,4,5,5 };

Please advice how to perform this logic and tried myList.Distinct() wouldn't help as it remove all the duplicates in the middle as well.

CodePudding user response:

    int topDuplicate = myList [0];
    myList .RemoveAll(x => x == topDuplicate);
    int bottomDuplicate = myList [myList .Count - 1];
    myList .RemoveAll(x => x == bottomDuplicate);

CodePudding user response:

var myList = new List<int> { 1, 1, 2, 2, 3, 4, 5, 5, 9, 9 };
    var topDublicate = myList.First();
    var lastDublicate = myList.Last();

    myList.RemoveAll(l => l == topDublicate);
    myList.RemoveAll(l => l == lastDublicate);
  • Related