📜  如何从 C# 中的数组中删除重复值?

📅  最后修改于: 2022-05-13 01:54:55.497000             🧑  作者: Mango

如何从 C# 中的数组中删除重复值?

数组是一组同质元素,它们由一个通用名称引用,并且可以包含重复值。在 C# 中,我们不能从指定的数组中删除元素,但我们可以创建一个包含不同元素的新数组。为此,我们使用 Distinct()函数。此函数给出与给定序列不同的值。如果给定数组为空,此方法将抛出 ArgumentNullException。

语法

array_name.Distinct()

其中 array_name 是一个输入数组。

例子:

Input  : data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 }
Output :
10
20
230
34
56
12
Input  : data = { "java", "java", "c", "python", "cpp", "c" }
Output :
java
c
python
cpp

方法

1.创建一个包含任何类型元素的数组,如 int、 字符串、float 等。

2.应用 distinct函数并转换为数组

data.Distinct().ToArray();

3.这里,ToArray() 方法转换数组中的值。

4.通过遍历数组来显示唯一元素

Array.ForEach(unique, i => Console.WriteLine(i));

示例 1:

C#
// C# program to remove duplicate elements from the array
using System;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare an array of integer type
    int[] data = { 10, 20, 230, 34, 56, 10, 12, 34, 56, 56 };
    Console.WriteLine("Array before removing duplicate values: ");
    Array.ForEach(data, i => Console.WriteLine(i));
      
    // Use distinct() function
    // To create an array that contain distinct values
    int[] unique = data.Distinct().ToArray();
      
    // Display the final result
    Console.WriteLine("Array after removing duplicate values: ");
    Array.ForEach(unique, j => Console.WriteLine(j));
}
}


C#
// C# program to remove duplicate elements from the array
using System;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare an array of string type
    string[] data1 = { "Java", "Java", "C", "Python", "CPP", "C" };
    Console.WriteLine("Array before removing duplicate values: ");
    Array.ForEach(data1, i => Console.WriteLine(i));
      
    // Use distinct() function
    // To create an array that contain distinct values
    string[] unique = data1.Distinct().ToArray();
      
    // Display the final result
    Console.WriteLine("Array after removing duplicate values: ");
    Array.ForEach(unique, j => Console.WriteLine(j));
}
}


输出:

Array before removing duplicate values:
10
20
230
34
56
10
12
34
56
56
Array after removing duplicate values:
10
20
230
34
56
12

示例 2:

C#

// C# program to remove duplicate elements from the array
using System;
using System.Linq;
  
class GFG{
  
public static void Main()
{
      
    // Declare an array of string type
    string[] data1 = { "Java", "Java", "C", "Python", "CPP", "C" };
    Console.WriteLine("Array before removing duplicate values: ");
    Array.ForEach(data1, i => Console.WriteLine(i));
      
    // Use distinct() function
    // To create an array that contain distinct values
    string[] unique = data1.Distinct().ToArray();
      
    // Display the final result
    Console.WriteLine("Array after removing duplicate values: ");
    Array.ForEach(unique, j => Console.WriteLine(j));
}
}

输出:

Array before removing duplicate values: 
Java
Java
C
Python
CPP
C
Array after removing duplicate values: 
Java
C
Python
CPP