c#中几种数据结构

数组型:

Array:内存连续分配,长度不可变,可索引访问。

ArrayList:早期版本使用,非泛型,类型不安全,如果元素数据类型不同可考虑使用。

List<>:泛型,可变长度,内存连续分配,只要内存是连续分配的都可以使用索引访问。

以上三种数据类型都是内存连续的,所以可以使用索引访问,增删改慢,索引查询快,实现IList、ICollection接口

链表型:

LinkedList<>:双向链表,元素不连续,所以不能使用索引访问,只能遍历查找,查找效率低,增删效率高。

Queue:先进先出,队列使用,可使用ConcurrentQueue保证线程安全

Stack:先进后出,可使用ConcurrentStack保证线程安全

以上三种数据类型内存不连续,所以不可以使用索引访问,增删改快,查慢,实现ICollection接口。

集合型:
Hashtable:老版本中使用,非泛型,线程安全,浪费空间

Hashset:查询效率高,所以如果元素较多,有查询需求,使用此类型。

Dictionary<>:非线程安全,可以使用ConcurrentDictionary

Hash分布,元素间没有关系,key不可重复。增删改查都快

SortedSet

List与HashSet查询性能比较:

        static void Main(string[] args)
        {
            List<Geography> geoList = new List<Geography>();
            HashSet<Geography> geoSet = new HashSet<Geography>();
            //添加30W测试数据
            for (int i = 0; i < 500000; i++)
            {
                geoSet.Add(new Geography { ID=i,Name="beijing",Type=2});
                geoList.Add(new Geography { ID = i, Name = "beijing", Type = 2 });
            }
            geoSet.Add(new Geography { ID = 100001, Name = "USA", Type = 1 });
            geoList.Add(new Geography { ID = 100001, Name = "USA", Type = 1 });

            Stopwatch sw = new Stopwatch();
            sw.Start();
            var item =geoList.FirstOrDefault(g => g.Name == "USA" && g.Type==1);
            sw.Stop();
           
            Console.WriteLine($"list耗时{ sw.ElapsedMilliseconds}");//list耗时13ms

            sw.Reset();
            item = geoSet.First(g => g.Name == "USA" && g.Type == 1);
            sw.Stop();
            Console.WriteLine($"set耗时{sw.ElapsedMilliseconds}");//set耗时0ms


            Console.ReadKey();
        }
    }
    public class Geography
    {
        public long ID { get; set; }
        public string Name { get; set; }
        public int Type { get; set; }

    }
原文地址:https://www.cnblogs.com/fanfan-90/p/11983734.html