zoukankan      html  css  js  c++  java
  • C#中的集合类

    集合相当于容器,用于将一系列相似的项组合在一起。

    集合可以分为泛型集合类和非泛型集合类。

    多数集合类都是派生自ICollection、IComparer、IEnumerable、IList、IDictionary和IDictionaryEnumerator接口以及它们的等效泛型接口,可继承这些接口来创建新集合类。

    ArrayList和List<T>

    • 相当于可以动态增删的动态数组
    •  内部有buffer,可以添加数据,buffer根据需要可以扩充

    栈:Stack<T>

    队列:Queue<T>

    双向链表:LinkedList<T>

    HashTable和Dictionary<TKey, Tvalue>

    •  相当于键值对的集合
    • 按照键进行查询时,比在List中搜索的效率要高,可用于程序优化

     

    •  用[]进行访问,表示获取,增加,删除,修改
    Dictionary<string, string> dic = new Dictionary<string, string>();
    dic.Add("Ton", "123");
    dic["Jane"] = "333";
    foreach(string key in dic.Keys)
    {
        Console.WriteLine(key + ":" + dic[key]);
    }

    为什么foreach既可以遍历数组,又可以遍历集合?

    for(类型  变量名  in xxx)

    • xxxx必须实现一个GetEnumerator方法,该方法返回一个IEnumerator对象
    • xxxx可以实现IEnumerable接口,来添加GetEnumerator方法 

    常用的集合类

    集合元素的排序

    1. 有序集合

    • SortedList<T>, SortedSet<T>, SortedDictionary<T>
    • 这些集合每插入就会排好序

    2. 使用集合的Sort方法

    • Array.Sort(arr, (a, b)=>a.Length-b.Length)
    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace 基础类学习
    {
        public class Test
        {
            public static void Main()
            {
                string[] arr = { "Apple", "Pearl", "Banana", "AA" };
                show(arr);
    
                //Array.Sort(arr);  // 默认按字典序
                Array.Sort(arr, (a, b) => a.Length - b.Length);
                show(arr);
    
                int i = Array.BinarySearch(arr, "Apple");
                Console.WriteLine(i);
    
                Array.Reverse(arr);
                show(arr);
            }
            public static void show(object[] arr)
            {
                foreach (object obj in arr)
                    Console.Write(obj + " ");
                Console.WriteLine();
            }
        }
    }
  • 相关阅读:
    巴洛克式和哥特式的区别
    推荐阅读书籍,是时候再行动起来了。
    AtCoder ABC 159F Knapsack for All Segments
    AtCoder ABC 159E Dividing Chocolate
    AtCoder ABC 158F Removing Robots
    AtCoder ABC 158E Divisible Substring
    AtCoder ABC 157F Yakiniku Optimization Problem
    AtCoder ABC 157E Simple String Queries
    AtCoder ABC 157D Friend Suggestions
    AtCoder ABC 156F Modularness
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14073598.html
Copyright © 2011-2022 走看看