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

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

 更新時間:2026年01月21日 09:38:04   作者:Never_Satisfied  
本文總結(jié)了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();

// 顯示結(jié)果
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收集不重復(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.針對復(fù)雜對象的去重

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ù)多個屬性去重
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. 對于簡單數(shù)據(jù)類型Distinct().ToArray() 通常是最佳選擇,代碼簡潔且性能良好
  2. 對于大型數(shù)組:使用 HashSet 的方法性能更好,時間復(fù)雜度為 O(n)
  3. 如果需要保留順序:使用自定義方法或 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:轉(zhuǎn)換為新List
List<string> uniqueFruits1 = fruits.Distinct().ToList();

// 方法2:就地修改(去除重復(fù)項后重新賦值)
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.擴展方法(封裝重用)

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

public static class ListExtensions
{
    // 擴展方法:去除重復(fù)項(返回新List)
    public static List<T> RemoveDuplicates<T>(this List<T> list)
    {
        return list.Distinct().ToList();
    }
    
    // 擴展方法:去除重復(fù)項(就地修改)
    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:全部轉(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;
}

// 或者使用容量優(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));
        
        // 處理大小寫敏感的場景
        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() - 最簡潔,適用于大多數(shù)場景
  2. HashSet<T>構(gòu)造函數(shù) - 性能最好,特別適合大數(shù)據(jù)量
  3. ForEach + Contains - 最簡單易懂,但性能最差(O(n²))

推薦選擇:

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

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

相關(guān)文章

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

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

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

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

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

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

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

    Unity UGUI Button按鈕組件使用示例

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

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

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

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

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

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

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

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

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

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

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

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

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

最新評論

姚安县| 东乌珠穆沁旗| 镇康县| 蓬溪县| 抚顺县| 大姚县| 张家港市| 青海省| 洞口县| 石嘴山市| 密云县| 漳州市| 邛崃市| 从江县| 门头沟区| 泰州市| 高阳县| 孙吴县| 穆棱市| 龙井市| 肇庆市| 民权县| 观塘区| 九龙坡区| 利川市| 寻乌县| 清远市| 繁昌县| 肥乡县| 绍兴县| 汉川市| 兴和县| 丹寨县| 进贤县| 泽普县| 沿河| 卢湾区| 通州区| 乌海市| 台安县| 新平|