Remove two int from three consecutive values from List<int>

Viewed 122

I use Winforms and C#. And I have more than 300 integers in a list and this is short example:

List<int> lst = new List<int>();
lst.Add(4);
lst.Add(25);
lst.Add(26);
lst.Add(27);
lst.Add(38);
lst.Add(51);
lst.Add(52);
lst.Add(53);
lst.Add(75);
//Etc.

I need to remove values (25, 26) but keep 27. Then again remove values (51, 52) but keep 53.. etc.

So basically if three consecutive values such as (1, 2, 3) are found, we need to remove (1, 2) and keep value (3).

As far as attempts are concerned, I couldn't scratch my head around any solution so far therefore I would appreciate any help.

Thanks

2 Answers

You could try the following. The key is marking the items to remove by detecting the sequence and picking the first two.

var excludeList = lst.Distinct()
                     .GroupBy(num => 
                                 Enumerable.Range(num, int.MaxValue - num + 1)
                                 .TakeWhile(lst.Contains)
                                 .Last()) 
                     .Where(seq => seq.Count() >= 3)
                     .SelectMany(seq => seq.OrderBy(num => num).Take(2));


var result = lst.Where(x=> !excludeList.Contains(x));

Output

4 
27 
38 
53 
75 

You can try this:

    static void Test()
    {
      var list = new List<int>();
      list.Add(4);
      list.Add(25);
      list.Add(26);
      list.Add(27);
      list.Add(38);
      list.Add(51);
      list.Add(52);
      list.Add(53);
      list.Add(75);
      var result = new List<int>();
      int count = list.Count;
      bool passover;
      if ( count > 0 )
        for ( int index = 0; index < count; )
        {
          passover = false;
          if ( index < count - 3 )
          {
            int v1 = list[index];
            int v2 = list[index + 1];
            int v3 = list[index + 2];
            if ( v3 == v2 + 1 && v2 == v1 + 1 )
              passover = true;
          }
          if ( passover )
          {
            result.Add(list[index + 2]);
            index += 3;
          }
          else
          {
            result.Add(list[index]);
            index++;
          }
        }
      foreach ( var item in result )
        Console.WriteLine(item);
    }

Output:

4
27
38
53
75
Related