最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#數(shù)組去重的方法匯總

 更新時(shí)間:2026年01月21日 09:38:04   作者:Never_Satisfied  
本文總結(jié)了C#中數(shù)組和List類型去重的多種方法,包括使用LINQ的Distinct()方法、HashSet、GroupBy方法等,文章還比較了不同方法的性能,并推薦了針對(duì)不同場(chǎng)景的最佳方法,需要的朋友可以參考下

數(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();

// 字符串?dāng)?shù)組去重
string[] uniqueFruits = fruits.Distinct().ToArray();

// 顯示結(jié)果
Console.WriteLine(string.Join(", ", uniqueNumbers)); // 1, 2, 3, 4, 5
Console.WriteLine(string.Join(", ", uniqueFruits));  // apple, orange, banana

2.使用 HashSet(自動(dòng)去重)

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收集不重復(fù)元素
HashSet<int> set = new HashSet<int>();
List<int> result = new List<int>();

foreach (int num in numbers)
{
    if (set.Add(num)) // 如果成功添加(表示不重復(fù))
    {
        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.針對(duì)復(fù)雜對(duì)象的去重

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" } // 重復(fù)
};

// 根據(jù)Id去重
Person[] uniquePeople = people
    .GroupBy(p => p.Id)
    .Select(g => g.First())
    .ToArray();

// 根據(jù)多個(gè)屬性去重
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();
}

性能比較

  1. 對(duì)于簡(jiǎn)單數(shù)據(jù)類型Distinct().ToArray() 通常是最佳選擇,代碼簡(jiǎn)潔且性能良好
  2. 對(duì)于大型數(shù)組:使用 HashSet 的方法性能更好,時(shí)間復(fù)雜度為 O(n)
  3. 如果需要保留順序:使用自定義方法或 Distinct()(它也會(huì)保留順序)

簡(jiǎn)單示例

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();
    }
}

推薦使用:對(duì)于大多數(shù)情況,使用 Distinct().ToArray() 是最簡(jiǎn)單直接的方法。如果需要處理自定義比較邏輯或特定性能需求,再考慮其他方法。

List<>類型

對(duì)于 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:轉(zhuǎn)換為新List
List<string> uniqueFruits1 = fruits.Distinct().ToList();

// 方法2:就地修改(去除重復(fù)項(xiàng)后重新賦值)
fruits = fruits.Distinct().ToList();

// 顯示結(jié)果
Console.WriteLine(string.Join(", ", uniqueFruits1)); // apple, orange, banana

2.使用 HashSet 的構(gòu)造函數(shù)(高效去重)

List<string> fruits = new List<string> { "apple", "orange", "apple", "banana", "orange" };

// 方法1:直接創(chuàng)建HashSet再轉(zhuǎn)回List
HashSet<string> hashSet = new HashSet<string>(fruits);
List<string> uniqueFruits = hashSet.ToList();

// 方法2:使用HashSet構(gòu)造函數(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.擴(kuò)展方法(封裝重用)

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

public static class ListExtensions
{
    // 擴(kuò)展方法:去除重復(fù)項(xiàng)(返回新List)
    public static List<T> RemoveDuplicates<T>(this List<T> list)
    {
        return list.Distinct().ToList();
    }
    
    // 擴(kuò)展方法:去除重復(fù)項(xiàng)(就地修改)
    public static void RemoveDuplicatesInPlace<T>(this List<T> list)
    {
        var uniqueItems = list.Distinct().ToList();
        list.Clear();
        list.AddRange(uniqueItems);
    }
    
    // 擴(kuò)展方法:使用自定義比較器去重
    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" };

// 使用擴(kuò)展方法
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:全部轉(zhuǎn)換為小寫/大寫后去重
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;
}

// 或者使用容量?jī)?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); // 預(yù)設(shè)容量
    List<string> result = new List<string>(list.Count); // 預(yù)設(shè)容量
    
    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));
        
        // 處理大小寫敏感的場(chǎng)景
        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));
    }
}

性能比較和建議

  1. Distinct().ToList() - 最簡(jiǎn)潔,適用于大多數(shù)場(chǎng)景
  2. HashSet<T>構(gòu)造函數(shù) - 性能最好,特別適合大數(shù)據(jù)量
  3. ForEach + Contains - 最簡(jiǎn)單易懂,但性能最差(O(n²))

推薦選擇:

  • 一般情況:使用 fruits.Distinct().ToList()
  • 性能敏感:使用 new HashSet<string>(fruits).ToList()
  • 需要自定義比較:使用 Distinct(StringComparer.OrdinalIgnoreCase).ToList()

以上就是C#數(shù)組去重的方法匯總的詳細(xì)內(nèi)容,更多關(guān)于C#數(shù)組去重方法的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C#實(shí)現(xiàn)一階卡爾曼濾波算法的示例代碼

    C#實(shí)現(xiàn)一階卡爾曼濾波算法的示例代碼

    這篇文章主要介紹了C#實(shí)現(xiàn)一階卡爾曼濾波算法的示例代碼,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-04-04
  • c#執(zhí)行excel宏模版的方法

    c#執(zhí)行excel宏模版的方法

    這篇文章主要介紹了c#執(zhí)行excel宏模版的方法,導(dǎo)出Excel模版的代碼如下,大家參考使用吧
    2014-01-01
  • C#云存儲(chǔ)服務(wù)的訪問控制與權(quán)限管理的全面指南

    C#云存儲(chǔ)服務(wù)的訪問控制與權(quán)限管理的全面指南

    在云計(jì)算時(shí)代,云存儲(chǔ)服務(wù)的訪問控制與權(quán)限管理是保障數(shù)據(jù)安全的基石,無論是AWS S3、Azure Blob Storage還是阿里云OSS,權(quán)限配置不當(dāng)可能導(dǎo)致數(shù)據(jù)泄露、未授權(quán)訪問甚至惡意攻擊,本文給大家介紹了C#云存儲(chǔ)服務(wù)的訪問控制與權(quán)限管理的全面指南,需要的朋友可以參考下
    2025-08-08
  • Unity UGUI Button按鈕組件使用示例

    Unity UGUI Button按鈕組件使用示例

    這篇文章主要為大家介紹了Unity UGUI Button按鈕組件使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-08-08
  • 詳解WPF如何使用WriteableBitmap提升Image性能

    詳解WPF如何使用WriteableBitmap提升Image性能

    這篇文章主要為大家詳細(xì)介紹了WPF如何使用WriteableBitmap提升Image性能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-01-01
  • 使用C#控制Excel單元格編輯權(quán)限的操作方法

    使用C#控制Excel單元格編輯權(quán)限的操作方法

    在團(tuán)隊(duì)協(xié)作與數(shù)據(jù)流轉(zhuǎn)日益頻繁的今天,保護(hù)?Excel?文檔中的關(guān)鍵數(shù)據(jù)免受意外修改或未經(jīng)授權(quán)的編輯,已成為保障數(shù)據(jù)完整性的基礎(chǔ)要求,本文將系統(tǒng)介紹如何使用?Free?Spire.XLS?for?.NET?庫(kù),在?C#?中精準(zhǔn)鎖定?Excel?工作表的特定單元格、行或列
    2026-05-05
  • C#中如何使用Winform實(shí)現(xiàn)炫酷的透明動(dòng)畫界面

    C#中如何使用Winform實(shí)現(xiàn)炫酷的透明動(dòng)畫界面

    這篇文章講解了如何使用Winform實(shí)現(xiàn)炫酷的透明動(dòng)畫界面,Winform相對(duì)于Wpf使用更簡(jiǎn)單一些,系統(tǒng)要求更低,需要了解的朋友可以參考下
    2015-07-07
  • 關(guān)于c#中枚舉類型支持顯示中文的擴(kuò)展說明

    關(guān)于c#中枚舉類型支持顯示中文的擴(kuò)展說明

    需求?。骸∶杜e類型在界面顯示的時(shí)候可以顯示相應(yīng)的中文信息, 這樣界面對(duì)用戶友好 . 場(chǎng)景 : 在一些業(yè)務(wù)中涉及到審核功能的時(shí)候, 往往有這幾個(gè)狀態(tài) :未送審 , 審核中 ,審核通過, 駁回?。∵@個(gè)時(shí)候我們會(huì)定義一個(gè)枚舉類型來描述 :
    2013-03-03
  • C#?webApi創(chuàng)建與發(fā)布、部署、api調(diào)用詳細(xì)教程

    C#?webApi創(chuàng)建與發(fā)布、部署、api調(diào)用詳細(xì)教程

    這篇文章主要給大家介紹了關(guān)于C#?webApi創(chuàng)建與發(fā)布、部署、api調(diào)用的相關(guān)資料,WebApi是微軟在VS2012?MVC4版本中綁定發(fā)行的,WebApi是完全基于Restful標(biāo)準(zhǔn)的框架,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下
    2023-12-12
  • C# 循環(huán)判斷會(huì)進(jìn)來幾次的實(shí)現(xiàn)代碼

    C# 循環(huán)判斷會(huì)進(jìn)來幾次的實(shí)現(xiàn)代碼

    這篇文章主要介紹了C# 循環(huán)判斷會(huì)進(jìn)來幾次的實(shí)現(xiàn)代碼,代碼中就一個(gè)循環(huán),循環(huán)的判斷是從一個(gè)函數(shù)獲取值,需要的朋友可以參考下
    2018-06-06

最新評(píng)論

聂荣县| 华池县| 北票市| 永春县| 谷城县| 克东县| 安达市| 马龙县| 射洪县| 泰来县| 万盛区| 南陵县| 巴林右旗| 永春县| 响水县| 科尔| 广水市| 出国| 新乡市| 志丹县| 合山市| 维西| 绥芬河市| 平武县| 景宁| 扬州市| 进贤县| 剑川县| 建昌县| 临邑县| 松滋市| 开阳县| 清涧县| 读书| 夹江县| 丘北县| 临汾市| 清水河县| 抚顺县| 和林格尔县| 略阳县|