Tour rookie C # ----- collection

Before learning the set we need to first look at the collection:

       Set indicates a set of objects may be accessed by traversing each element (in particular, can be used to access the foreach loop).

Collections and arrays difference: 

 

 

 

  Save number Word length RAM Traversing speed
Array fixed fixed Small footprint fast
set flexible Variable length Multi-occupancy slow

Functionally, all functions can be realized by an array of collection can be implemented; conversely certain set of functions that can be realized, it is difficult to achieve the array

  Array Collection (List)  
Defined format: Data Type [] variable name; List <Data Type> variable name;  
Assignment

= New variable name Data type [length]

Since the fixed length data, so that the assignment must be specified length

 

 

Variable name = new List <Data Type>  
initialization = New variable name Data type [length] {element 1, element 2, ...} Variable name = new List <data type> element of {1, 2} element;  
Since the collection of variable length, the collection can add, insert, delete, modify elements

 

 

 

Adding elements:

Variable name .add (data to be added)

Wherein the type of data to be added as and when a predetermined set of definitions

 
   

Insert elements:

Variable names .Insert (index data to be inserted)

 
   

Removing elements:

Variable names .RemoveAt (index)

Delete the specified index element

Variable names .Remove (data)

Delete the collection of data and fill in the same first match

 
change the data Variable name. [Index] = value Two identical  
Gets the number of elements Variable names .Length Variable names .Count  

 

Array is the C # first appeared, although his index very fast, but any course, there are some deficiencies, insert data between two data arrays are very troublesome, but also in the statement must specify the data array length, type and the like.

       In response to these cut-off point of the array, C # provides ArrayList object to overcome these drawbacks

example:

ArrayList list1 = new ArrayList();  
//新增数据  
list1.Add("cde");  
list1.Add(5678);  
//修改数据  
list[2] = 34;  
//移除数据  
list.RemoveAt(0);  
//插入数据  
list.Insert(0, "qwe"); 

Examples of the above, we inserted both in the set of string type, also inserted values, the different types are allowed to ArrayList, as will all ArrayList inserted therein as data object type to handle, it is not security type.

Therefore ArrayList typically operated in the boxing and unboxing occur when storing or retrieving a value type, great consumption.

The so-called transfer box and unboxing is:

Packing: The value type of the data package to an instance of a reference type

Unpacking: extract values ​​from the reference type

 

ArrayList (non-generic collections) and List (generic collections)

LIST most of its usage is similar to the ArrayList, because the List class also inherits IList interface. The key difference is that when you declare a List collection, we also need for the type of object List collection of data within the declaration.

 list = new List<string>();  
//新增数据  
list.Add(“abc”);  
//修改数据  
list[0] = “def”;  
//移除数据  
list.RemoveAt(0);

 to sum up: 

   Capacity of the array is fixed, You can only get or set a value of the element, while the ArrayList or a List <T> can automatically expand capacity as needed, modify, delete or insert data.

    Arrays can have multiple dimensions, and ArrayList or List <T> always has only one dimension.

example:

{//随机的在这个list集合中添加十个数字,不能重复,求和,求最大值,求最小值,求平均值
            List<int> list = new List<int>();   //实例化,表示要在list中存放整数
                    Random r = new Random();
            int num = 0;

            while (list.Count!=10)
            {
                 num = r.Next(100);//表示产生一个0~9之间的随机数
                if (!list.Contains(num))//判断list中有没有当前的num值 
                {
                    list.Add(num);
                }
                list.Add(num);
                

            }
            //求最大值
            Console.WriteLine("最大值:{0}", list.Max());
            Console.WriteLine("最小值:{0}", list.Min());
            Console.WriteLine("综合:{0}",list.Sum() );
            Console.WriteLine("平均值:{0}", list.Average());

List of other methods:

List.clear // remove all elements

Whether there is the element List.contains () // compare collection

List.indexof () // current index position

 

In fact, there are a set of very similar and the ---- dictionary :

Examples of the dictionary format:

Dictionary<string, string> dic = new Dictionary<string, string>();
            //Dictionary<键值,value>  
            dic.Add("老苏", "凤姐");
            dic.Add("老牛", "芙蓉姐姐");
            Dictionary<int, string> myIdc = new Dictionary<int, string>();
            myIdc.Add(1, "haha");
想要遍历整个字典: 

 foreach (string item in dic.Keys)
            {
                Console.WriteLine("key---{0},vlaue---{1}", item, dic[item]);
                //item 表示键值   dic.[item] ---- 相当于 value
            }
            Console.ReadKey();

Hash tables:

//哈希表,以键值的形式存储,key----键   value---值;
        static void Main(string[] args)
        {

            Hashtable ht = new Hashtable();
            ht.Add("老苏","001");
            ht.Add("小马", 003);
            ht.Add(new Person("小洋", '男', 18), 005);

May store any type of data, but the data is stored can not be repeated 

Key-value pairs are object types

Features: disordered

Traversal methods hash table:

foreach(var item in ht.keys)//代表单个的key
{
     console.writeline(ht[item])// item可以改变名

}
//ht[item] 键值对应的value

一个小例子:
static void Main(string[] args)
        {
            Hashtable ht = new Hashtable();

            ArrayList al = new ArrayList();


            //哈希表 以键值对的形式存值   key -----键    value-----值
            //无序的
            ht.Add("老苏", "1001");

            ht.Add("小马",1002);
            ht.Add(1003,"老牛");
            ht.Add(new Person("小杨",'男',18),1005);

            ht.Add("小赵","老马");


            

            ht.Remove(1003);
            Console.WriteLine("{0}-----{1}","老苏",ht["老苏"]);
            Console.WriteLine("===========================");
           
            foreach (object str in ht.Values)
            {
                //Console.WriteLine("key{0},-------value{1}",str,ht[str]);
               //如果我们把 ht.keys  转换为  ht.values ,
               //那么str就不是索引 而是值 可以直接显示出来
                Console.WriteLine(str);  
            }



            Console.WriteLine("添加成功了");

            Console.ReadKey();

Summary and set of generic hash tables and dictionaries differences and similarities:  

Guess you like

Origin blog.csdn.net/qq_30631063/article/details/85785218