C#數(shù)組去重的方法匯總
更新時間:2026年01月21日 09:38:04 作者:Never_Satisfied
本文總結了C#中數(shù)組和List類型去重的多種方法,包括使用LINQ的Distinct()方法、HashSet、GroupBy方法等,文章還比較了不同方法的性能,并推薦了針對不同場景的最佳方法,需要的朋友可以參考下
數(shù)組類型
在C#中給數(shù)組去重有多種方法,以下是幾種常用的方式:
1.使用 LINQ 的 Distinct() 方法(最常用)
using System;
using System.Linq;
int[] numbers = { 1, 2, 2, 3, 4, 4, 5 };
string[] fruits = { "apple", "orange", "apple", "banana" };
// 整數(shù)數(shù)組去重
int[] uniqueNumbers = numbers.Distinct().ToArray();
// 字符串數(shù)組去重
string[] uniqueFruits = fruits.Distinct().ToArray();
// 顯示結果
Console.WriteLine(string.Join(", ", uniqueNumbers)); // 1, 2, 3, 4, 5
Console.WriteLine(string.Join(", ", uniqueFruits)); // apple, orange, banana
2.使用 HashSet(自動去重)
using System;
using System.Collections.Generic;
int[] numbers = { 1, 2, 2, 3, 4, 4, 5 };
// 方法1:直接創(chuàng)建HashSet
HashSet<int> hashSet = new HashSet<int>(numbers);
int[] uniqueNumbers = hashSet.ToArray();
// 方法2:使用HashSet收集不重復元素
HashSet<int> set = new HashSet<int>();
List<int> result = new List<int>();
foreach (int num in numbers)
{
if (set.Add(num)) // 如果成功添加(表示不重復)
{
result.Add(num);
}
}
int[] uniqueArray = result.ToArray();
3.使用 LINQ 的 GroupBy 方法
using System;
using System.Linq;
int[] numbers = { 1, 2, 2, 3, 4, 4, 5 };
int[] uniqueNumbers = numbers
.GroupBy(x => x)
.Select(g => g.Key)
.ToArray();
4.自定義去重方法(不依賴LINQ)
using System;
using System.Collections.Generic;
public static T[] RemoveDuplicates<T>(T[] array)
{
List<T> result = new List<T>();
HashSet<T> seen = new HashSet<T>();
foreach (T item in array)
{
if (seen.Add(item)) // 如果元素是新出現(xiàn)的
{
result.Add(item);
}
}
return result.ToArray();
}
// 使用示例
int[] numbers = { 1, 2, 2, 3, 4, 4, 5 };
int[] uniqueNumbers = RemoveDuplicates(numbers);
5.針對復雜對象的去重
using System;
using System.Linq;
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
Person[] people =
{
new Person { Id = 1, Name = "Alice" },
new Person { Id = 2, Name = "Bob" },
new Person { Id = 1, Name = "Alice" } // 重復
};
// 根據(jù)Id去重
Person[] uniquePeople = people
.GroupBy(p => p.Id)
.Select(g => g.First())
.ToArray();
// 根據(jù)多個屬性去重
Person[] uniquePeople2 = people
.GroupBy(p => new { p.Id, p.Name })
.Select(g => g.First())
.ToArray();
6.保留原始順序的去重方法
using System;
using System.Collections.Generic;
public static T[] RemoveDuplicatesKeepOrder<T>(T[] array)
{
var seen = new HashSet<T>();
var result = new List<T>();
foreach (var item in array)
{
if (!seen.Contains(item))
{
seen.Add(item);
result.Add(item);
}
}
return result.ToArray();
}
性能比較
- 對于簡單數(shù)據(jù)類型:
Distinct().ToArray()通常是最佳選擇,代碼簡潔且性能良好 - 對于大型數(shù)組:使用
HashSet的方法性能更好,時間復雜度為 O(n) - 如果需要保留順序:使用自定義方法或
Distinct()(它也會保留順序)
簡單示例
using System;
using System.Linq;
class Program
{
static void Main()
{
// 示例1:基本去重
int[] numbers = { 1, 2, 3, 2, 4, 3, 5 };
int[] unique = numbers.Distinct().ToArray();
// 示例2:字符串去重
string[] words = { "hello", "world", "hello", "c#" };
string[] uniqueWords = words.Distinct().ToArray();
// 示例3:使用自定義比較器
string[] caseInsensitive = { "Hello", "hello", "WORLD", "world" };
string[] uniqueCaseInsensitive = caseInsensitive
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
}
}
推薦使用:對于大多數(shù)情況,使用 Distinct().ToArray() 是最簡單直接的方法。如果需要處理自定義比較邏輯或特定性能需求,再考慮其他方法。
List<>類型
對于 List<string> 類型的去重操作,方法與數(shù)組類似但更靈活,以下是幾種常用方式:
1.使用 LINQ 的 Distinct() 方法(推薦)
using System;
using System.Collections.Generic;
using System.Linq;
List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };
// 方法1:轉換為新List
List<string> uniqueFruits1 = fruits.Distinct().ToList();
// 方法2:就地修改(去除重復項后重新賦值)
fruits = fruits.Distinct().ToList();
// 顯示結果
Console.WriteLine(string.Join(", ", uniqueFruits1)); // apple, orange, banana
2.使用 HashSet 的構造函數(shù)(高效去重)
List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };
// 方法1:直接創(chuàng)建HashSet再轉回List
HashSet<string> hashSet = new HashSet<string>(fruits);
List<string> uniqueFruits = hashSet.ToList();
// 方法2:使用HashSet構造函數(shù)并指定比較器(如忽略大小寫)
HashSet<string> caseInsensitiveSet = new HashSet<string>(
fruits,
StringComparer.OrdinalIgnoreCase
);
List<string> uniqueCaseInsensitive = caseInsensitiveSet.ToList();
3.使用 ForEach 循環(huán)和 Contains 檢查
List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };
List<string> uniqueList = new List<string>();
foreach (string fruit in fruits)
{
if (!uniqueList.Contains(fruit))
{
uniqueList.Add(fruit);
}
}
// 或者使用ForEach方法
List<string> uniqueList2 = new List<string>();
fruits.ForEach(fruit =>
{
if (!uniqueList2.Contains(fruit))
uniqueList2.Add(fruit);
});
4.使用 LINQ 的 GroupBy 方法
List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };
List<string> uniqueFruits = fruits
.GroupBy(f => f)
.Select(g => g.Key)
.ToList();
5.擴展方法(封裝重用)
using System;
using System.Collections.Generic;
using System.Linq;
public static class ListExtensions
{
// 擴展方法:去除重復項(返回新List)
public static List<T> RemoveDuplicates<T>(this List<T> list)
{
return list.Distinct().ToList();
}
// 擴展方法:去除重復項(就地修改)
public static void RemoveDuplicatesInPlace<T>(this List<T> list)
{
var uniqueItems = list.Distinct().ToList();
list.Clear();
list.AddRange(uniqueItems);
}
// 擴展方法:使用自定義比較器去重
public static List<T> RemoveDuplicates<T>(
this List<T> list,
IEqualityComparer<T> comparer)
{
return list.Distinct(comparer).ToList();
}
}
// 使用示例
List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };
// 使用擴展方法
List<string> unique1 = fruits.RemoveDuplicates();
fruits.RemoveDuplicatesInPlace();
// 使用自定義比較器(忽略大小寫)
List<string> mixedCase = new List<string> { "Apple", "apple", "ORANGE", "Orange" };
List<string> unique2 = mixedCase.RemoveDuplicates(StringComparer.OrdinalIgnoreCase);
6.處理大小寫敏感的去重
List<string> mixedCase = new List<string> { "Apple", "apple", "ORANGE", "Orange", "banana", "BANANA" };
// 方法1:全部轉換為小寫/大寫后去重
List<string> uniqueLower = mixedCase
.Select(s => s.ToLower())
.Distinct()
.ToList();
// 方法2:使用忽略大小寫的比較器
List<string> uniqueCaseInsensitive = mixedCase
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
// 方法3:保留原始大小寫形式(第一次出現(xiàn)的)
List<string> uniquePreserveCase = mixedCase
.GroupBy(s => s, StringComparer.OrdinalIgnoreCase)
.Select(g => g.First())
.ToList();
7.性能優(yōu)化的去重方法
public static List<string> RemoveDuplicatesFast(List<string> list)
{
if (list == null || list.Count == 0)
return new List<string>();
HashSet<string> seen = new HashSet<string>();
List<string> result = new List<string>();
foreach (string item in list)
{
if (seen.Add(item)) // 如果成功添加到HashSet(說明是新的)
{
result.Add(item);
}
}
return result;
}
// 或者使用容量優(yōu)化
public static List<string> RemoveDuplicatesOptimized(List<string> list)
{
if (list == null || list.Count == 0)
return new List<string>();
HashSet<string> seen = new HashSet<string>(list.Count); // 預設容量
List<string> result = new List<string>(list.Count); // 預設容量
foreach (string item in list)
{
if (seen.Add(item))
{
result.Add(item);
}
}
result.TrimExcess(); // 釋放多余容量
return result;
}
8.完整示例
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// 創(chuàng)建示例數(shù)據(jù)
List<string> fruits = new List<string>
{
"apple", "orange", "apple", "banana", "orange", "grape", "banana"
};
Console.WriteLine("原始列表: " + string.Join(", ", fruits));
// 方法1:使用Distinct
List<string> method1 = fruits.Distinct().ToList();
Console.WriteLine("Distinct方法: " + string.Join(", ", method1));
// 方法2:使用HashSet
List<string> method2 = new HashSet<string>(fruits).ToList();
Console.WriteLine("HashSet方法: " + string.Join(", ", method2));
// 方法3:就地修改
fruits = fruits.Distinct().ToList();
Console.WriteLine("就地修改后: " + string.Join(", ", fruits));
// 處理大小寫敏感的場景
List<string> caseSensitive = new List<string>
{
"Apple", "apple", "APPLE", "Orange", "orange"
};
Console.WriteLine("\n大小寫敏感列表: " + string.Join(", ", caseSensitive));
// 忽略大小寫去重
List<string> caseInsensitive = caseSensitive
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
Console.WriteLine("忽略大小寫去重: " + string.Join(", ", caseInsensitive));
}
}
性能比較和建議
Distinct().ToList()- 最簡潔,適用于大多數(shù)場景HashSet<T>構造函數(shù)- 性能最好,特別適合大數(shù)據(jù)量ForEach + Contains- 最簡單易懂,但性能最差(O(n²))
推薦選擇:
- 一般情況:使用
fruits.Distinct().ToList() - 性能敏感:使用
new HashSet<string>(fruits).ToList() - 需要自定義比較:使用
Distinct(StringComparer.OrdinalIgnoreCase).ToList()
以上就是C#數(shù)組去重的方法匯總的詳細內(nèi)容,更多關于C#數(shù)組去重方法的資料請關注腳本之家其它相關文章!
相關文章
C#如何提取經(jīng)緯度文件中的經(jīng)緯度數(shù)據(jù)
近期開發(fā)時需要獲取當前的經(jīng)緯度坐標,下面這篇文章主要給大家介紹了關于C#如何提取經(jīng)緯度文件中經(jīng)緯度數(shù)據(jù)的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2022-08-08
c#只讀字段和常量的區(qū)別,以及靜態(tài)構造函數(shù)的使用實例
這篇文章主要介紹了c#只讀字段和常量的區(qū)別,以及靜態(tài)構造函數(shù)的使用實例,有需要的朋友可以參考一下2013-12-12
c# SQLHelper(for winForm)實現(xiàn)代碼
數(shù)據(jù)連接池c# SQLHelper 實現(xiàn)代碼2009-02-02
淺談C#手機號換成111XXXX1111 這種顯示的解決思路
下面小編就為大家?guī)硪黄獪\談C#手機號換成111XXXX1111 這種顯示的解決思路。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11

