30秒学会 C# 片段 · 2018年1月7日

30秒学会 C# 片段 – KeepUpToN

Filters a collection keeping up to n occurences of each value.

Use IEnumerable.Distinct() in combination with IEnumerable.ToDictionary() to create a dictionary with an initial count of 0 for each distinct value in data.
Use IEnumerable.Where() to filter out occurences after the nth one for each element, using the previously created dictionary.

代码实现

using System.Collections.Generic;
using System.Linq;

public static partial class _30s 
{
  public static IEnumerable<T> KeepUpToN<T>(IEnumerable<T> data, int n)
  {
    var occurences = data.Distinct().ToDictionary(i => i, value => 0);
    return data.Where(i => occurences[i]++ < n);
  }
}

使用样例

int[] nums = {1, 1, 2, 3, 3, 3, 1};

_30s.KeepUpToN(nums, 2); // {1, 1, 2, 3, 3}