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

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

 更新時間:2022年05月09日 17:13:39   作者:springsnow  
這篇文章介紹了C#中的列表List<T>、HashSet和只讀集合,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

一、概述

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): 從指定集合(如數(shù)組)復(fù)制元素進行初始化。

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

三、常用屬性和方法

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、刪除范圍內(nèi)的元素:

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>中的元素實現(xiàn)了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屬性:實際包含的元素數(shù);

Capacity:能夠容納的元素總數(shù);

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

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、順序翻轉(zhuǎn)

mList.Reverse()//index,count

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

7、轉(zhuǎn)換:

1、將一定范圍內(nèi)的元素從List<T>復(fù)制到兼容的一維數(shù)組中。

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

2、將List<T>中的元素復(fù)制到新數(shù)組中。

string[] arr=mList.ToArray();

3、創(chuàng)建源List<T>的元素范圍的淺表副本。

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

4、將當(dāng)前List<T>的元素轉(zhuǎn)換成另一種類型,返回轉(zhuǎn)換后元素的列表

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>轉(zhuǎn)成用逗號分隔的字符串

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

8、去掉重復(fù)項(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>不能使用索引訪問,不能存儲重復(fù)數(shù)據(jù),元素T必須實現(xiàn)了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" };//傳統(tǒng)隊
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,將指定對象元素添加到當(dāng)前對象(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的區(qū)別

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

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

五、鏈表 LinkedList

鏈表是一串存儲數(shù)據(jù)的鏈式數(shù)據(jù)結(jié)構(gòu),它的每個成員都有額外的兩個空間來關(guān)聯(lián)它的上一個成員和下一個成員。

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

1、鏈表的內(nèi)存表視圖

2、實例:

static void Main(string[] args)
{
    LinkedList<Document> linkedlist = new LinkedList<Document>();
    //添加節(jié)點
    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
    //查找節(jié)點
    LinkedListNode<Document> findnode = linkedlist.FindLast(doc);
    Display(findnode.Value); //title:3

    //插入節(jié)點
    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

    //移除節(jié)點
    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);
    }
}

到此這篇關(guān)于C#列表List<T>、HashSet和只讀集合介紹的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • C# list<T>去重的實現(xiàn)

    C# list<T>去重的實現(xiàn)

    List集合在開發(fā)過程中很常見,經(jīng)常我們要對該集合進行一系列操作,本文主要介紹了C# list<T>去重的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下
    2023-12-12
  • 簡單的excel導(dǎo)入導(dǎo)出示例分享

    簡單的excel導(dǎo)入導(dǎo)出示例分享

    這篇文章主要介紹了簡單的excel導(dǎo)入導(dǎo)出示例分享,需要的朋友可以參考下
    2014-03-03
  • C#組合模式實例詳解

    C#組合模式實例詳解

    這篇文章主要介紹了C#組合模式,實例分析了C#實現(xiàn)組合模式的原理與相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-07-07
  • C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼

    C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼

    這篇文章主要介紹了C# 實現(xiàn)TXT文檔轉(zhuǎn)Table的示例代碼,幫助大家更好的理解和學(xué)習(xí)c#,感興趣的朋友可以了解下
    2020-12-12
  • C#讀取Excel并轉(zhuǎn)化成XML的方法

    C#讀取Excel并轉(zhuǎn)化成XML的方法

    這篇文章主要介紹了C#讀取Excel并轉(zhuǎn)化成XML的方法,實例分析了C#操作Excel及XML文件的技巧,具有一定參考借鑒價值,需要的朋友可以參考下
    2015-04-04
  • Unity3D應(yīng)用之時鐘與鐘表小組件的使用教程

    Unity3D應(yīng)用之時鐘與鐘表小組件的使用教程

    這篇文章主要來和大家詳細介紹一下Unity3D應(yīng)用開發(fā)中的時鐘和鐘表小組件的使用,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-01-01
  • C#?中的partial?關(guān)鍵字詳解

    C#?中的partial?關(guān)鍵字詳解

    這篇文章主要介紹了C#?中的partial?關(guān)鍵字,partial 關(guān)鍵字用于拆分一個類、一個結(jié)構(gòu)、一個接口或一個方法的定義到兩個或更多的文件中,本文通過實例代碼給大家介紹的非常詳細,需要的朋友可以參考下
    2022-07-07
  • C#圖像亮度調(diào)式與偽彩色圖的處理教程(推薦)

    C#圖像亮度調(diào)式與偽彩色圖的處理教程(推薦)

    下面小編就為大家推薦一篇C#圖像亮度調(diào)式與偽彩色圖的處理教程,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2017-11-11
  • C# newtonsoft.json中文亂碼問號的解決方案

    C# newtonsoft.json中文亂碼問號的解決方案

    這篇文章主要介紹了C# newtonsoft.json中文亂碼問號的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 基于C#實現(xiàn)簡單的音樂播放器

    基于C#實現(xiàn)簡單的音樂播放器

    這篇文章主要介紹了如何基于C#實現(xiàn)簡單的音樂播放器,考慮到需求中的界面友好和跨版本兼容性,我們可以選擇選擇Windows Forms作為開發(fā)平臺,Windows Forms提供了一個簡單而強大的方法來創(chuàng)建桌面應(yīng)用程序,文中通過代碼示例給大家講解的非常詳細,需要的朋友可以參考下
    2024-05-05

最新評論

河南省| 永福县| 上栗县| 亳州市| 平塘县| 体育| 同江市| 尖扎县| 南阳市| 宁安市| 舒城县| 蒙城县| 饶平县| 屯留县| 阳朔县| 鲁甸县| 施秉县| 丰城市| 尉犁县| 柳林县| 邹平县| 哈巴河县| 濮阳县| 游戏| 昆山市| 宜兰市| 普格县| 松潘县| 平顶山市| 崇仁县| 宁安市| 汉阴县| 浦江县| 都昌县| 枣强县| 大方县| 徐汇区| 平顺县| 庆城县| 海伦市| 饶平县|