日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#列表List<T>、HashSet和只讀集合介紹_C#教程

作者:springsnow ? 更新時間: 2022-07-03 編程語言

一、概述

List<T> 是ArrayList類的等效泛型類。屬System.Collections.Generic命名空間。

二、聲明及初始化

1、List<T> mList=new List<T>([capacity]) :可帶初始容量

List<string> mList=new List<string>();

2、List<T> mList=new List<T><IEnumerable<T> collection): 從指定集合(如數組)復制元素進行初始化。

List<string> mList0 = new List<string>(new []{ "a", "b", "c" } );//數組
List<string> mList1 = new List<string>("a,b,c".Split(new char[] {','}) );//將字符串轉成List<string>
List<string> mList2 = new List<string> { "a", "b", "c" };//集合初始值設定項

三、常用屬性和方法

1、添加元素

1、添加一個元素:

mList.Add("a");

2、添加一組元素

mList.AddRange(new [] { new Person("a", 20), new Person("b", 10), }

3、在Index處插入一個元素

mList.Insert(0,"d");//以前占此及此位以后的元素都往后移動

4、在Index處插入一組元素:

mList.InsertRange(0,new []{"E","f"});

2、刪除元素

1、刪除一個值:

mList.Remove("a");

2、刪除索引處的元素:

mList.RemoveAt(0);
for (int i = mList.Count - 1; i >= 0; i--)
{ }

3、刪除范圍內的元素:

mList.RemoveRange(3, 2);//index,count

4、清空所有元素:

mList.Clear();

5、刪除與指定條件匹配的所有元素:

mList.RemoveAll(p => p.Length > 1);//bool Predicate<T>(T matach)? 委托

注意:Remove()、Contais()、IndexOf、LastIndexOf()方法需要使用“相等”比較器。?
List<T>中的元素實現了IEquatable接口則使用其Equals()方法,否則默認使用Object.Equals(object)。

3、訪問列表元素以及遍歷列表:

1、用索引的形式訪問

mList[0]

2、遍歷

foreach (string s in mList)
{
    Console.WriteLine(s);
}

for (int i = 0; i < mList.Count; i++)
{
    Console.WriteLine(s);
}

注意:Count屬性:實際包含的元素數;

Capacity:能夠容納的元素總數;

TrimExcess()方法可將容量調整為實際容量。

4、判斷元素存在:

1、判斷整個元素是否存在該List中:

if (mList.Contains("d"))
    { }

2、判斷是否存在于指定條件匹配的元素:

if (mList.Exists(p => p.Length > 2))
    { }

3、判讀是否List中每個元素都與指定條件匹配:

if (mList.TrueForAll(p => p.Length > 2))
 {}

5、搜索:

查找索引

1、查找列表中某個項的第一個索引:

mList.IndexOf(T,[index],[count]);

2、查找某元素在列表中最后一個匹配 項的索引:

mList.LastIndexOf(T,[index],[count]);

3、查找與指定條件匹配的元素在列表中第一個匹配項的索引:

mList.FindIndex([startIndex],[count],match);

4、查找與指定條件匹配的元素在列表中最后一個匹配項的索引:

mList.FindLastIndex(2, 10, p => p.Length > 2);

查找元素:

1、查找與指定條件匹配的元素,返回第一個匹配元素:

string find= mList.Find( p => p.Length > 2);

2、查找與指定條件匹配的元素,返回最后一個匹配元素:

string find= mList.FindLast( p => p.Length > 2);

3、查找并返回與指定條件匹配的元素列表:

List<string> finds= mList.FindAll( p => p.Length > 2);

6、排序:

委托簽名:

int Comparison<T>(T x, T y);

1、使用Comparision<T>委托進行元素排序:

mList.Sort((x, y) =>
    {
        int result = x[0].CompareTo(y[0]);
        if (result == 0) { return x[1].CompareTo(y[1]); }
        return result;
    });

2、順序翻轉

mList.Reverse()//index,count

注意:Sort方法還可以利用ICompable和Icomparer接口排序。

7、轉換:

1、將一定范圍內的元素從List<T>復制到兼容的一維數組中。

mList.CopyTo([index],array,[arrryIndex],[count]);

2、將List<T>中的元素復制到新數組中。

string[] arr=mList.ToArray();

3、創建源List<T>的元素范圍的淺表副本。

List(string) range= mList.GetRange(inex,count);

4、將當前List<T>的元素轉換成另一種類型,返回轉換后元素的列表

List<char> chars=mList.ConvertAll(p=>p[0]);
List<Racer> RacerList=PList.ConvertAll<Person,Racer>(p=>new Racer(p.FirstName+" " +p.LastName));

Converter委托簽名:

TOutput Converter<in TInput,out TOutput>(TInput input);

5、將List<string>轉成用逗號分隔的字符串

string  aa= String.Join(",",mList)

8、去掉重復項(Distinct)

需要引用using System.Linq;

1、默認比較器:

mList.Distinct().ToList();

2、自定義比較器

mList.Distinct(new MyComparer()).ToList();
public class MyComparer : System.Collections.Generic.IEqualityComparer<string>
{
    public bool Equals(string x, string y)
    {
        return x.ToUpper()==y.ToUpper();
    }

    public int GetHashCode(string obj)
    {
        return obj.ToUpper().GetHashCode();
    }
}

9、只讀集合

List的AsReadOnly()方法返回ReadOnlyCollection,所有修改方法拋出NotSupportedException異常。

System.Collections.ObjectModel.ReadOnlyCollection readOnlyList= mList.AsReadOnly();

四:HashSet<T>

?? 用來存儲集合,基于Hash,可理解為沒有Value,只有Key的Dictionary<TKey,TValue);

  • HashSet<T>不能使用索引訪問,不能存儲重復數據,元素T必須實現了Equals和GetHashCode方法;
  • HashSet<T>的檢索性能比List<T>好得多。如Contains(),Remove();
  • HashSet<T>是專門用來和集合運算(取并集、交集等),所以提供了UnionWith(),InterSetWith()等方法。

1、常用方法

Add、IsSubsetOf、IsSupersetOf、Overlaps、UnionWith

var companyTeams = new HashSet<string> { "Ferrari", "McLaren", "Mercedes" };//公司隊
var traditionalTeams = new HashSet<string> { "Ferrari", "McLaren" };//傳統隊
var privateTeams = new HashSet<string> { "Red Bull", "Toro Rosso", "Force India", "Sauber" };//私有隊

//Add方法,將一個元素添加到集中,成功返回true失敗返回false
if (privateTeams.Add("Williams"))//返回true
    Console.WriteLine("Williams Add Success.privateTeams count:{0}", privateTeams.Count);
if (!companyTeams.Add("McLaren"))//返回false
    Console.WriteLine("McLaren Add Failure.companyTeams count:{0}", companyTeams.Count);

//IsSubset,確認(traditionalTeams)對象是否為指定集(companyTeams)的子集
if (traditionalTeams.IsSubsetOf(companyTeams))//traditionalTeams是companyTeams的子集,返回true
    Console.WriteLine("traditionalTeams is sub of companyTeams.");

//IsSuperset,確認(companyTeams)對象是否為指定集(traditionalTeams)的超集(父集)
if (companyTeams.IsSupersetOf(traditionalTeams))//companyTeams是traditionalTeams的父集,返回true
    Console.WriteLine("companyTeams is a superset of traditionalTeams");

//Overlaps,確認對象(privateTeams)和指定集(traditionalTeams)是否存在共同元素
traditionalTeams.Add("Williams");
if (privateTeams.Overlaps(traditionalTeams))//privateTeams和traditionalTeams都包含有Williams的元素,返回true
    Console.WriteLine("At least one team is the same with the traditionalTeams and privateTeams.");

//UnionWith,將指定對象元素添加到當前對象(allTeams)中,因為對象類型為SortedSet,所以是元素是唯一有序的
var allTeams = new SortedSet<string>();
allTeams.UnionWith(companyTeams);
allTeams.UnionWith(traditionalTeams);
allTeams.UnionWith(privateTeams);
foreach (var item in allTeams)
{
    Console.Write(item);
}

2、HashSet和SortedSet的區別

共同點:??
1. 都是集,都具有集的特征,包含的元素不能有重復

不同點:??
1. HashSet的元素是無序的,SortedSet的元素是有序的

五、鏈表 LinkedList

鏈表是一串存儲數據的鏈式數據結構,它的每個成員都有額外的兩個空間來關聯它的上一個成員和下一個成員。

所以,鏈表對于插入和刪除操作效率會高于ArrayList,因為它存儲了上一個成員和下一個成員的指針,進行插入和刪除只需要改變當前LinkedListNode的Previous和Next的指向即可。

1、鏈表的內存表視圖

2、實例:

static void Main(string[] args)
{
    LinkedList<Document> linkedlist = new LinkedList<Document>();
    //添加節點
    linkedlist.AddFirst(new Document("1"));
    linkedlist.AddFirst(new Document("2"));
    Display(linkedlist); //title:2   title:1

    Document doc = new Document("3");
    linkedlist.AddLast(doc);
    Document doc1 = new Document("4");
    linkedlist.AddLast(doc1);
    Display(linkedlist); //title:2   title:1  title:3   title:4
    //查找節點
    LinkedListNode<Document> findnode = linkedlist.FindLast(doc);
    Display(findnode.Value); //title:3

    //插入節點
    linkedlist.AddBefore(findnode, new Document("5"));
    Display(linkedlist); //title:2   title:1  title:5   title:3   title:4

    linkedlist.AddAfter(findnode, new Document("6"));
    Display(linkedlist); //title:2   title:1  title:5   title:3  title:6  title:4

    linkedlist.AddAfter(findnode.Previous, new Document("7"));
    Display(linkedlist); //title:2   title:1  title:5   title:7  title:3  title:6  title:4

    linkedlist.AddAfter(findnode.Next, new Document("8"));
    Display(linkedlist); //title:2   title:1  title:5   title:7  title:3  title:6  title:8  title:4

    //移除節點
    linkedlist.Remove(findnode);
    Display(linkedlist); //title:2   title:1  title:5   title:7  title:6  title:8  title:4

    linkedlist.Remove(doc1);
    Display(linkedlist); //title:2   title:1  title:5   title:7  title:6  title:8 

    linkedlist.RemoveFirst();
    Display(linkedlist); //title:1  title:5   title:7  title:6  title:8 

    linkedlist.RemoveLast();
    Display(linkedlist); //title:1  title:5   title:7  title:6
}

private static void Display<T>(LinkedList<T> linkedlist)
{
    foreach (var item in linkedlist)
    {
        Console.Write(item + " ");
    }
}

private static void Display<T>(T doc)
{
    Console.Write(doc);
}

public class Document
{
    public string title { get; private set; }
    public Document(string title)
    {
        this.title = title;
    }

    public override string ToString()
    {
        return string.Format("title:{0}", title);
    }
}

原文鏈接:https://www.cnblogs.com/springsnow/p/9428516.html

欄目分類
最近更新