In C # array array,arraylist, generic list detailed comparison _c# tutorial

Source: Internet
Author: User

In C #, the array array,arraylist, the generic list can store a group of objects, but in the development of not knowing which performance is the highest, below we analyze and analyze.

An array of arrays

An array is an ordered set of fixed sizes that store elements of the same type. An array is a collection of data that is commonly considered to be a collection of variables of the same type.

The array class is the base class for all arrays in C #, and it is defined in the System namespace.

Arrays are stored continuously in memory, so they are indexed very quickly, and the assignment and modification elements are also very simple.

Array Arrays Specific use:

Using System; Namespace WEBAPP {class Program {static void Main (string[] args) {//system.array//1, array [] specific type,
      Fixed length string[] str1 = new String[3];
      Str1[0] = "a";
      STR1[1] = "B";
      STR1[2] = "C";

      Console.WriteLine (Str1[2]);
      string[] str2 = new string[] {"A", "B", "C"};

      Console.WriteLine (Str2[0]);
      String[] Str3 = {"A", "B", "C"};
      Console.WriteLine (Str3[0]);
      2, two-dimensional array//int[,] intarray=new int[2,3]{{1,11,111},{2,22,222}};
      int[,] intarray = new int[2, 3];
      Intarray[0, 0] = 1;
      Intarray[0, 1] = 11;

      Intarray[0, 2] = 111;
      intarray[1, 0] = 2;
      Intarray[1, 1] = 22;
      Intarray[1, 2] = 222;
      Console.WriteLine ("{0},{1},{2}", Intarray[0, 0], intarray[0, 1], intarray[0, 2]);

      Console.WriteLine ("{0},{1},{2}", Intarray[1, 0], intarray[1, 1], intarray[1, 2]);
 3, multidimensional array int[,,] intArray1 = new int[,,] {{1, 1}, {11, 11}, {111, 111}},       {{2, 2}, {22, 22}, {222, 222}}, {{3, 3}, {33, 33}, {333, 333}}}; Console.WriteLine ("{0},{1},{2},{3},{4},{5}", intarray1[0, 0, 0], intarray1[0, 0, 1], intarray1[0, 1, 0], intarray1[0, 1, 1
      ], intarray1[0, 2, 0], intarray1[0, 2, 1]; Console.WriteLine ("{0},{1},{2},{3},{4},{5}", intarray1[1, 0, 0], intarray1[1, 0, 1], intarray1[1, 1, 0], intarray1[1, 1, 1
      ], intarray1[1, 2, 0], intarray1[1, 2, 1]; Console.WriteLine ("{0},{1},{2},{3},{4},{5}", intarray1[2, 0, 0], intarray1[2, 0, 1], intarray1[2, 1, 0], intarray1[2, 1, 1

      ], intarray1[2, 2, 0], intarray1[2, 2, 1];
      4, staggered array is an array of arrays int[][] IntArray2 = new int[4][];
      Intarray2[0] = new int[] {1};
      INTARRAY2[1] = new int[] {2, 22};
      INTARRAY2[2] = new int[] {3, 33, 333};
      INTARRAY2[3] = new int[] {4, 44, 444,4444}; for (int i = 0; i < intarray2.length i++) {for (int j = 0; J < Intarray2[i]. Length;
     J + +) {     Console.WriteLine ("{0}", Intarray2[i][j]);
    } console.readkey ();

 }
  }
}

Although the array stores retrieval data quickly, there are some drawbacks:

1. The length of the array must be specified when declaring the array, and it becomes cumbersome if the length of the array is not known.

2, the length of the array is too long, can cause memory waste, too short can cause data overflow error.

3, in the array of two data inserted between the data is very troublesome

More information on Microsoft Official documents: Array Class (System)

Second, ArrayList

Since arrays have many drawbacks, C # provides ArrayList objects to overcome these drawbacks.

ArrayList is a namespace system.collections that must be referenced when it is used, and inherits the IList interface, providing data storage and retrieval.

The size of the ArrayList object is dynamically augmented and contracted according to the data stored in it. Therefore, you do not need to specify the length of the ArrayList object when declaring it.

The default initial capacity of the ArrayList is 0. As the elements are added to the ArrayList, the capacity is automatically increased as needed through reallocation. You can reduce capacity by calling trimtosize or by explicitly setting the Capacity property.

Using System;
Using System.Collections;
public class Samplesarraylist {public

  static void Main () {

   ArrayList Myal = new ArrayList ();
   Myal.add ("Hello");
   Myal.add ("World");
   Myal.add ("!");

   Console.WriteLine ("Myal");
   Console.WriteLine ("  Count:  {0}", Myal.count);
   Console.WriteLine ("  Capacity: {0}", myal.capacity);
   Console.Write ("  Values:");
   Printvalues (Myal);
  }

  public static void Printvalues (IEnumerable myList) {
   foreach (Object obj. myList)
     Console.Write ("  {0 } ", obj);
   Console.WriteLine ();
   Console.readkey ();
  }



Run Result:

ArrayList solves all the drawbacks in the array, but boxing and unboxing operations typically occur when storing or retrieving value types, resulting in significant performance depletion. In particular, boxing operations, such as:

      ArrayList list = new ArrayList ();

      Add 
      list. ADD ("Joye.net");
      List. Add (a);

      Update 
      list[2] =;

      Delete 
      list. RemoveAt (0);

      Insert 
      list. Insert (0, "Joye.net1"); 

In the list, the string joye.net is inserted first, and int type 27 is inserted. This allows the insertion of different types of data in ArrayList. Because ArrayList will treat all inserted data as object types, it is possible to report type mismatch errors when using ArrayList to process data, that is, ArrayList is not type-safe.

More reference Microsoft Official ArrayList Document: ArrayList Class (System.Collections)

Three, the generic type list<t>

The concept of generics arises because of the arraylist of unsafe types and the disadvantages of box unboxing.

The List class is a generic equivalent class of the ArrayList class. This class implements the IList generic interface using an array of sizes that can be dynamically increased on demand, and most usages are similar to ArrayList.

List<t> is type-safe, when declaring a list collection, the type of object that must declare the data within the list collection.

Using System;

Using System.Collections.Generic;

    public class Example {public static void Main () {list<string> dinosaurs = new list<string> (); Console.WriteLine ("\ncapacity: {0}", dinosaurs.)

    Capacity); Dinosaurs.
    ADD ("Tyrannosaurus"); Dinosaurs.
    ADD ("Amargasaurus"); Dinosaurs.
    ADD ("Mamenchisaurus"); Dinosaurs.
    ADD ("Deinonychus"); Dinosaurs.

    ADD ("Compsognathus");
    Console.WriteLine ();
    foreach (string dinosaur in Dinosaurs) {Console.WriteLine (dinosaur); } Console.WriteLine ("\ncapacity: {0}", dinosaurs.)
    Capacity); Console.WriteLine ("Count: {0}", dinosaurs.)

    Count); Console.WriteLine ("\ncontains (\ deinonychus\"): {0} ", dinosaurs.

    Contains ("Deinonychus"));
    Console.WriteLine ("\ninsert" (2, \ "Compsognathus\")); Dinosaurs.

    Insert (2, "Compsognathus");
    Console.WriteLine ();
    foreach (string dinosaur in Dinosaurs) {Console.WriteLine (dinosaur); } Console.WriteLine ("\ndinosaurs[3]: {0}", Dinosaurs[3]);
    Console.WriteLine ("\nremove" ("compsognathus\")); Dinosaurs.

    Remove ("Compsognathus");
    Console.WriteLine ();
    foreach (string dinosaur in Dinosaurs) {Console.WriteLine (dinosaur); } dinosaurs.
    TrimExcess ();
    Console.WriteLine ("\ntrimexcess ()"); Console.WriteLine ("Capacity: {0}", dinosaurs.)
    Capacity); Console.WriteLine ("Count: {0}", dinosaurs.)

    Count); Dinosaurs.
    Clear ();
    Console.WriteLine ("\nclear ()"); Console.WriteLine ("Capacity: {0}", dinosaurs.)
    Capacity); Console.WriteLine ("Count: {0}", dinosaurs.)
  Count);

 }
}

If the object type that declares the data in the list collection is string, and then inserts an int type into the list collection, the error is 111,ide and cannot be compiled. Obviously this list<t> is type safe.

To encapsulate the return result set:

  public class resultdto<t>
  {public
    T Data {get; set;}
    public string Code {get; set;}
    public string: {get; set;}
  }

      var data = new cityentity ();
      return new Resultdto<cityentity> {data = data, Code = ' 1 ', message = ' sucess '};

      var data2 = new list<cityentity> ();
      return new Resultdto<list<cityentity>> {Data = data2, Code = "1", message = "sucess"};

      var data1 = 1;
      return new Resultdto<int> {Data = data1, Code = "1", message = "sucess"};

More reference Microsoft Official documents: List generic class

Iv. Summary

1, the capacity of the array is fixed, and the capacity of ArrayList or list<t> can be automatically expanded according to the need.

2. Arrays can have multiple dimensions, while ArrayList or list< t> always have only one dimension. (You can create lists of array lists or lists)

3. The performance of a particular type of array is superior to the performance of ArrayList (excluding Object, because the element of ArrayList is object and boxing and unboxing are usually occurred when a value type is stored or retrieved).

4, ArrayList and list<t> are basically equivalent, and if the type T of the list< t> class is a reference type, then the behavior of the two classes is exactly the same. If T is a value type, you need to consider the performance loss caused by boxing and unboxing. List<t> is type safe.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.