30秒学会 C# 片段 · 2019年12月23日

30秒学会 C# 片段 – DistinctValues

Returns all distinct values in a collection.

Use IEnumerable.Distinct() to get the distinct values in the given collection.

代码实现

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

public static partial class _30s 
{
  public static IEnumerable<T> DistinctValues<T>(IEnumerable<T> data) 
  {
    return data.Distinct();
  }
}

使用样例

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

_30s.DistinctValues(nums); // { 1, 2, 3, 4, 5 }