C#列表List<T>、HashSet和只讀集合介紹
一、概述
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ù)制元素進(jìn)行初始化。
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è)定項(xiàng)
三、常用屬性和方法
1、添加元素
1、添加一個(gè)元素:
mList.Add("a");
2、添加一組元素
mList.AddRange(new [] { new Person("a", 20), new Person("b", 10), }
3、在Index處插入一個(gè)元素
mList.Insert(0,"d");//以前占此及此位以后的元素都往后移動(dòng)
4、在Index處插入一組元素:
mList.InsertRange(0,new []{"E","f"});
2、刪除元素
1、刪除一個(gè)值:
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>中的元素實(shí)現(xiàn)了IEquatable接口則使用其Equals()方法,否則默認(rèn)使用Object.Equals(object)。
3、訪問(wèn)列表元素以及遍歷列表:
1、用索引的形式訪問(wèn)
mList[0]
2、遍歷
foreach (string s in mList) { Console.WriteLine(s); } for (int i = 0; i < mList.Count; i++) { Console.WriteLine(s); }
注意:Count屬性:實(shí)際包含的元素?cái)?shù);
Capacity:能夠容納的元素總數(shù);
TrimExcess()方法可將容量調(diào)整為實(shí)際容量。
4、判斷元素存在:
1、判斷整個(gè)元素是否存在該List中:
if (mList.Contains("d")) { }
2、判斷是否存在于指定條件匹配的元素:
if (mList.Exists(p => p.Length > 2)) { }
3、判讀是否List中每個(gè)元素都與指定條件匹配:
if (mList.TrueForAll(p => p.Length > 2)) {}
5、搜索:
查找索引
1、查找列表中某個(gè)項(xiàng)的第一個(gè)索引:
mList.IndexOf(T,[index],[count]);
2、查找某元素在列表中最后一個(gè)匹配 項(xiàng)的索引:
mList.LastIndexOf(T,[index],[count]);
3、查找與指定條件匹配的元素在列表中第一個(gè)匹配項(xiàng)的索引:
mList.FindIndex([startIndex],[count],match);
4、查找與指定條件匹配的元素在列表中最后一個(gè)匹配項(xiàng)的索引:
mList.FindLastIndex(2, 10, p => p.Length > 2);
查找元素:
1、查找與指定條件匹配的元素,返回第一個(gè)匹配元素:
string find= mList.Find( p => p.Length > 2);
2、查找與指定條件匹配的元素,返回最后一個(gè)匹配元素:
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>委托進(jìn)行元素排序:
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)成用逗號(hào)分隔的字符串
string aa= String.Join(",",mList)
8、去掉重復(fù)項(xiàng)(Distinct)
需要引用using System.Linq;
1、默認(rèn)比較器:
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>
用來(lái)存儲(chǔ)集合,基于Hash,可理解為沒(méi)有Value,只有Key的Dictionary<TKey,TValue);
- HashSet<T>不能使用索引訪問(wèn),不能存儲(chǔ)重復(fù)數(shù)據(jù),元素T必須實(shí)現(xiàn)了Equals和GetHashCode方法;
- HashSet<T>的檢索性能比List<T>好得多。如Contains(),Remove();
- HashSet<T>是專門用來(lái)和集合運(yùn)算(取并集、交集等),所以提供了UnionWith(),InterSetWith()等方法。
1、常用方法
Add、IsSubsetOf、IsSupersetOf、Overlaps、UnionWith
var companyTeams = new HashSet<string> { "Ferrari", "McLaren", "Mercedes" };//公司隊(duì) var traditionalTeams = new HashSet<string> { "Ferrari", "McLaren" };//傳統(tǒng)隊(duì) var privateTeams = new HashSet<string> { "Red Bull", "Toro Rosso", "Force India", "Sauber" };//私有隊(duì) //Add方法,將一個(gè)元素添加到集中,成功返回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,確認(rèn)(traditionalTeams)對(duì)象是否為指定集(companyTeams)的子集 if (traditionalTeams.IsSubsetOf(companyTeams))//traditionalTeams是companyTeams的子集,返回true Console.WriteLine("traditionalTeams is sub of companyTeams."); //IsSuperset,確認(rèn)(companyTeams)對(duì)象是否為指定集(traditionalTeams)的超集(父集) if (companyTeams.IsSupersetOf(traditionalTeams))//companyTeams是traditionalTeams的父集,返回true Console.WriteLine("companyTeams is a superset of traditionalTeams"); //Overlaps,確認(rèn)對(duì)象(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,將指定對(duì)象元素添加到當(dāng)前對(duì)象(allTeams)中,因?yàn)閷?duì)象類型為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ū)別
共同點(diǎn):
1. 都是集,都具有集的特征,包含的元素不能有重復(fù)
不同點(diǎn):
1. HashSet的元素是無(wú)序的,SortedSet的元素是有序的
五、鏈表 LinkedList
鏈表是一串存儲(chǔ)數(shù)據(jù)的鏈?zhǔn)綌?shù)據(jù)結(jié)構(gòu),它的每個(gè)成員都有額外的兩個(gè)空間來(lái)關(guān)聯(lián)它的上一個(gè)成員和下一個(gè)成員。
所以,鏈表對(duì)于插入和刪除操作效率會(huì)高于ArrayList,因?yàn)樗鎯?chǔ)了上一個(gè)成員和下一個(gè)成員的指針,進(jìn)行插入和刪除只需要改變當(dāng)前LinkedListNode的Previous和Next的指向即可。
1、鏈表的內(nèi)存表視圖
2、實(shí)例:
static void Main(string[] args) { LinkedList<Document> linkedlist = new LinkedList<Document>(); //添加節(jié)點(diǎn) 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é)點(diǎn) LinkedListNode<Document> findnode = linkedlist.FindLast(doc); Display(findnode.Value); //title:3 //插入節(jié)點(diǎn) 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é)點(diǎn) 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和只讀集合介紹的文章就介紹到這了。希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)軟件監(jiān)控外部程序運(yùn)行狀態(tài)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)軟件監(jiān)控外部程序運(yùn)行狀態(tài)的方法,可實(shí)現(xiàn)監(jiān)控另一個(gè)程序的運(yùn)行狀態(tài)及觸發(fā)相應(yīng)事件的功能,是非常實(shí)用的技巧,需要的朋友可以參考下2014-12-12C#簡(jiǎn)單實(shí)現(xiàn)在網(wǎng)頁(yè)上發(fā)郵件的案例
本文分享一個(gè)C#利用SMTP發(fā)送郵件的案例,提供了前后臺(tái)代碼,方便大家學(xué)習(xí)。2016-03-03C#事件處理和委托event delegate實(shí)例簡(jiǎn)述
這篇文章主要介紹了C#事件處理和委托event delegate的簡(jiǎn)單實(shí)例,較為詳細(xì)的講述了C#事件處理和委托的聲明與實(shí)現(xiàn)過(guò)程,代碼簡(jiǎn)單易懂,需要的朋友可以參考下2014-09-09Unity UGUI的Scrollbar滾動(dòng)條組件使用詳解
這篇文章主要介紹了Unity UGUI的Scrollbar(滾動(dòng)條)組件的介紹及使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07ASP.NET MVC 5使用X.PagedList.Mvc進(jìn)行分頁(yè)教程(PagedList.Mvc)
這篇文章主要介紹了ASP.NET MVC 5使用X.PagedList.Mvc進(jìn)行分頁(yè)教程(原名為PagedList.Mvc),需要的朋友可以參考下2014-10-10