zoukankan      html  css  js  c++  java
  • C#中的Collection 1

    Collection定义

    Collection是个关于一些变量的集合,按功能可分为Lists,Dictionaries,Sets三个大类。

    1. Lists:是一个有序的集合,支持index look up。
      • Array
      • List<T>
    2. Dictionaries:同TKey store 一些TValue集合,没有特定order
    3. Sets:用来form collections into onther collection,比如HashSet<T>

    Collection提供的一些公共方法

    是Collection就至少会有Enumerat,但是不一定都有Look up(比如Sets就没有,Statcks和Queues也是有自己的固定排列顺序,不提供look up的方法),注意List的look up用index,而Dictionary的look up用Key。

    For adding和removing的位置可能也不一样,list可以指定加和减的位置,而Statck是先进先出

    Array

    1: 有Fixed size并且是固定从上到下的顺序储存,index从0开始。

     1  static void Main(string[] args)
     2         {
     3             //Declare
     4             string[] daysOfWeek ={
     5                                     "Monday",
     6                                     "Tuesday",
     7                                     "Wednesday",
     8                                     "Thurday",
     9                                     "Friday",
    10                                     "Saturday",
    11                                     "Sunday"
    12                                 };
    13             Console.WriteLine("Type in index of day of look up>");
    14             int index = int.Parse(Console.ReadLine());
    15 
    16             //look up using index
    17             Console.WriteLine(daysOfWeek[index]);
    18 
    19             //Enumerates
    20             foreach (string day in daysOfWeek)
    21             {
    22                 Console.WriteLine(day);
    23             }
    24 
    25             //replace
    26             daysOfWeek[5] = "PartyDay";
    27         }
    View Code
    • 由于Array是固定size,所以没有Add和Remove item

     2: Array是reference type,有两种initialize

    int[] x4 = new int[5];  //这个5不可以省
    int[] x5 = new int[5] {1, 4, 9, 16, 25};  //可以全部写出来
    int[] x5 = new int[] {1, 4, 9, 16, 25};  //让compiler来认有几个元素
    var x5 = {1, 4, 9, 16, 25};  //int[]可以换成var,后面赋值都可以都不写int[]

             int eight = 8;
                int[] square = new int[]{
                    1,
                    2 * 2,
                    eight + 1,
                    int.Parse("16"),
                    (int)Math.Sqrt(625)
                };

    3: Enumerating

    这里出现错误,foreach 的interation plceholder是只读的reference type,for不是

    比较上面array[i]会改变原array里的元素,下面则不会

    4: For VS Foreach

    For:Can replace an array element,must directly access it using the index not using foreach

    Foreach: Can't replace element(只读) but can modify value of elements,对其他readonly collection也一样

     1  class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             Person[] student = new Person[]
     6            {
     7                 new Person{Name = "Shawn", Age = 33},
     8                 new Person{Name = "Yawei", Age = 30}
     9            };
    10             //foreach的iteration placeholder是只读不可以改
    11             //我们这里没有直接改这个reference
    12             //指定的每个person object,比如指向别的object
    13             //而是修改这个object里面的值
    14             foreach (Person person in student)
    15             {
    16                 person.Age = 20;
    17             }
    18 
    19             foreach (Person person in student)
    20             {
    21                 Console.WriteLine(person);
    22             }
    23             Console.ReadLine();
    24         }
    25 
    26     }
    27     public class Person
    28     {
    29         public string Name{get; set;}
    30         public int Age{get; set;}
    31         public override string ToString()
    32         {
    33             return string.Format("{0} 's age = {1}", Name, Age);
    34         }
    35     }
    View Code

     在collection里包括array == 是判断reference是否相等的,而不是值。

    Derived reference can used in place of base reference(this can apply to all collections)

    static void Main(string[] args)
            {
                Human[] human = new Human[]
                {
                    new Human{Name = "Shawn", Age = 33},
                    new Human{Name = "Yawei", Age = 30}
                };
                human[0] = new Employee { Name = "Tutu", Age=12, Salary=120.2f};
            }
            public class Employee : Human
            {
                public float Salary { get; set; }
            }
            public class Human{
                public string Name { get; set; }
                public int Age { get; set; }
            }
    View Code

    5: Convariance

     

    static void Main(string[] args)
            {
                object[] obj1 = new object[3];
                string[] daysOfWeeks = {
                                           "Monday",
                                           "Tuesday",
                                           "Wendesday"
                                       };
                //this can work
                obj1[0] = 3;
    
                //这个是reference type,obj2 point to daysOfWeeks's location
                object[] obj2 = daysOfWeeks;
                //这句有问题,因为refer的地址是一个string[] type
                //compile time的时候VS发现不了问题,会直接给runtime 带来break的后果
                //same result as daysOfWeeks[0] = 3;
                obj2[0] = 3;
                daysOfWeeks[0] = 3;
            }
    View Code

     解释:

    一般Convariance不允许用在Collection(List<T>, Dictionial<TKey, TValue>)上即Collection of derived type to a collection of base type,即使像上面用在了array上也会有或许被broke掉的危险。

    但是enumerator,enumerable可以做convariance,因为他们是只读的type保证是安全的,不会修改collection。

    var strList = new List<string>{"Monday","Tuesday"};
    
    List<object> objList = (List<Object>)strList;
    //compiler will show error, can not do this kind of covariance
    
    IEnumerable<object> objEnum = strList;
    //this can do

    6: Array的方法

    一般有普通Array方法或者LINQ方法,Array方法tend to work in-place,而LINQ总是tend to return new object

    Copy:

    • Array.CopyTo(普通)
    • ToArray(LINQ)

    Reverse:

    • Array.Reverse(普通,static方法)
    • var reversed = daysOfWeek.Reverse(); (LINQ方法)

    注意LINQ方法经常return IEnumerable 而不是Array,如果需要变为Array要在后面加一个.ToArray

     

     Sort:

    Array.Sort

    Array.Sort([T], comparer)

    IEnumerable<T>.OrderBy();

    Binary Search:

    Array.BinarySearch([T], "Sunday")

    Search

    Find item in array: Array.IndexOf(), Array.LastIndexOf()

    Find item with condition in array: Array.FindIndex([T], x=> x[0] == 'W'), Array.FindAll([T], x=> x.length == 6)

  • 相关阅读:
    C++11 并发指南三(Lock 详解)
    C++11 并发指南六(atomic 类型详解四 C 风格原子操作介绍)
    C++11 并发指南六(atomic 类型详解三 std::atomic (续))
    C++11 并发指南六( <atomic> 类型详解二 std::atomic )
    C++11 并发指南六(atomic 类型详解一 atomic_flag 介绍)
    C++11 并发指南五(std::condition_variable 详解)
    腾讯地图定位及坐标解析
    控制器里把文件转为二进制输出下载
    C#操作mongodb简记
    MYSQL备份还原问题
  • 原文地址:https://www.cnblogs.com/shawnzxx/p/3678569.html
Copyright © 2011-2022 走看看