C#列表List<T>、HashSet和只读集合介绍

目录
  • 一、概述
  • 二、声明及初始化
  • 三、常用属性和方法
    • 1、添加元素
    • 2、删除元素
    • 3、访问列表元素以及遍历列表:
    • 4、判断元素存在:
    • 5、搜索:
    • 6、排序:
    • 7、转换:
    • 8、去掉重复项(Distinct)
    • 9、只读集合
  • 四:HashSet<T>
    • 1、常用方法
    • 2、HashSet和SortedSet的区别
  • 五、链表 LinkedList
    • 1、链表的内存表视图
    • 2、实例:

一、概述

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

到此这篇关于C#列表List<T>、HashSet和只读集合介绍的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 关于C#泛型列表List<T>的基本用法总结

    示例代码如下:namespace SampleListT{  class Program  {      static void Main(string[] args)      {//using System.Collections.Generic; 命名空间中的List<T>//using System.Collections; 命名空间中的ArrayList  //都实现了列表集合,一个是泛形集合,一个是非泛型的//下面我们将Person对象加到集合中 Person p1 = new P

  • c# HashSet的扩容机制需要注意的

    一:背景 1. 讲故事 自从这个纯内存项目进了大客户之后,搞得我现在对内存和CPU特别敏感,跑一点数据内存几个G的上下,特别没有安全感,总想用windbg抓几个dump看看到底是哪一块导致的,是我的代码还是同事的代码? 很多看过我博客的老朋友总是留言让我出一套windbg的系列或者视频,我也不会呀,没办法,人在江湖飘,迟早得挨上几刀,逼着也得会几个花架子

  • C# ArrayList、HashSet、HashTable、List、Dictionary的区别详解

    在C#中,数组由于是固定长度的,所以常常不能满足我们开发的需求. 由于这种限制不方便,所以出现了ArrayList. ArrayList.List<T> ArrayList是可变长数组,你可以将任意多的数据Add到ArrayList里面.其内部维护的数组,当长度不足时,会自动扩容为原来的两倍. 但是ArrayList也有一个缺点,就是存入ArrayList里面的数据都是Object类型的,所以如果将值类型存入和取出的时候会发生装箱.拆箱操作(就是值类型与引用类型之间的转换),这个会影响程序性能

  • C#列表List<T>、HashSet和只读集合介绍

    目录 一.概述 二.声明及初始化 三.常用属性和方法 1.添加元素 2.删除元素 3.访问列表元素以及遍历列表: 4.判断元素存在: 5.搜索: 6.排序: 7.转换: 8.去掉重复项(Distinct) 9.只读集合 四:HashSet<T> 1.常用方法 2.HashSet和SortedSet的区别 五.链表 LinkedList 1.链表的内存表视图 2.实例: 一.概述 List<T> 是ArrayList类的等效泛型类.属System.Collections.Generi

  • Python中列表、字典、元组、集合数据结构整理

    本文详细归纳整理了Python中列表.字典.元组.集合数据结构.分享给大家供大家参考.具体分析如下: 列表: 复制代码 代码如下: shoplist = ['apple', 'mango', 'carrot', 'banana'] 字典: 复制代码 代码如下: di = {'a':123,'b':'something'} 集合: 复制代码 代码如下: jihe = {'apple','pear','apple'} 元组: 复制代码 代码如下: t = 123,456,'hello' 1.列表 空

  • Python字符串、列表、元组、字典、集合的补充实例详解

    本文实例讲述了Python字符串.列表.元组.字典.集合.分享给大家供大家参考,具体如下: 附加: python的很多编译器提供了代码补全功能,并且在填入参数时提供提示功能 字符串 1.常用函数: 字符串是不可变对象,字符串的方法都不会改变原字符串的数据 s=" hEllo world!\t " print("s.capitalize():",s.capitalize())#标题格式化 print("s.center(20,'-'):",s.ce

  • Python中的集合介绍

    1.集合的定义 集合的元素是不可重复的 s = {1,2,3,1,2,3,4,5} print(s) print(type(s)) s1 = {1} print(s1) print(type(s1)) 集合就算只有一个元素,也是集合,不需要像列表一样,加个逗号 那么如何定义一个空集合 s2 = {} print(type(s2)) s3 = set([]) print(s3) print(type(s3)) 集合的应用(去重) li = [1,2,3,1,2,3] print(list(set(

  • C# 列表List的常用属性和方法介绍

    1.创建列表 (列表可以存储任何类型的数据,在创建列表对象的时候首先要指定你要创建的这个列表要存储什么类型的)(泛型) //创建列表 //方法一 List<int> intList = new List<int>();//创建了一个空的列表 通过类型后面的<>来表示这个列表存储的数据的类型 //方法二 var intlist1 = new List<string>(); //方法三 var intlist2 = new List<int>(){1

  • Python基础学习之基本数据结构详解【数字、字符串、列表、元组、集合、字典】

    本文实例讲述了Python基础学习之基本数据结构.分享给大家供大家参考,具体如下: 前言 相比于PHP,Python同样也是脚本解析语言,所以在使用Python的时候,变量和数据结构相对于编译语言来说都会简单许多,但是Python相比于PHP来说,变量类型的定义会比较严格:string->int的转换没有PHP那么方便.但这也让程序稳定性有所提升,例如和客户端交互的时候,数据库取出来的数字int和缓存取出来的数字(默认是string)需要手动进行转换(否则会有报错提示),而PHP不需要手动转换的

  • C#集合之列表的用法

    目录 1.创建列表 2.添加元素 3.插入元素 4.访问元素 5.删除元素 6.搜索 7.排序 8.类型转换 9.只读集合 .NET Framework为动态列表List提供泛型类List<T>.这个类实现了IList,ICollection,IEnumerable,IList<T>,ICollection<T>,IEnumerable<T>接口. 1.创建列表 创建一个赛车手类,下面的例子会用到: public class Racer : ICompara

  • Java 详解Collection集合之ArrayList和HashSet

    目录 Collection List ArrayList Set HashSet ArrayList和HashSet的区别 泛型 Collection Collection接口被List接口和Set接口继承 本章只介绍常用的集合 List ArrayList是List接口的实现类 ArrayList ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素. ArrayList 继承了 AbstractList ,并实现了 List 接口

  • Java 详解Collection集合之ArrayList和HashSet

    目录 Collection List ArrayList Set HashSet ArrayList和HashSet的区别 泛型 Collection Collection接口被List接口和Set接口继承 本章只介绍常用的集合 List ArrayList是List接口的实现类 ArrayList ArrayList 类是一个可以动态修改的数组,与普通数组的区别就是它是没有固定大小的限制,我们可以添加或删除元素. ArrayList 继承了 AbstractList ,并实现了 List 接口

  • Python列表和集合的效率大比拼

    目录 程序运行效率 数据查找效率 数据存储开销 程序运行效率 程序的运行效率分为两种:第一种是时间效率,第二种是空间效率.时间效率被称为时间复杂度,而空间效率被称作空间复杂度.时间复杂度主要衡量的是一个程序的运行速度,而空间复杂度主要衡量一个程序所需要的额外存储空间. 一个程序执行所耗费的时间,从理论上说,是不能算出来的,只有你把程序放在机器上跑起来,才能知道,不同机器不同时间得出的结果可能不一样.但是我们需要每个程序都上机测试吗?显然不现实,所以才有了时间复杂度这个分析方式.实际中我们计算时间

随机推荐