Search code examples
c#algorithmlinqextract

C# Extract that removes from source as many records as many in second


We have two arrays

int[] arr1 = new int[] { 1, 1, 1, 2, 3 };
int[] arr2 = new int[] { 1, 2 };

I am looking for Linq (not necessary) method that accepts these two collections and returns

{ 1, 1, 3 }

The problems is that Intersect returns { 3 }


Solution

  • You can compute frequencies of the items to remove (arr2) and then remove them from arr1

    var freq = arr2
      .GroupBy(item => item)
      .ToDictionary(group => group.Key, group => group.Count());
    
    var result = arr1
      .Where(item => !freq.ContainsKey(item) || --freq[item] >= 0)
      .ToArray();