C# 0 The Complete Reference


Obtaining an Array from an ArrayList



Download 4,07 Mb.
Pdf ko'rish
bet944/1096
Sana23.01.2022
Hajmi4,07 Mb.
#402171
1   ...   940   941   942   943   944   945   946   947   ...   1096
Bog'liq
C-Sharp 3 The Complete Reference Herbert Schildt

Obtaining an Array from an ArrayList 

When working with 



ArrayList

, you will sometimes want 

to obtain an actual array that contains the contents of the list. You can do this by calling 

ToArray( )

. There are several reasons why you might want to convert a collection into an 

array. Here are two: You may want to obtain faster processing times for certain operations, 

or you might need to pass an array to a method that is not overloaded to accept a collection. 

Whatever the reason, converting an 

ArrayList

 to an array is a trivial matter, as the following 

program shows:

// Convert an ArrayList into an array.

using System;

using System.Collections;

class ArrayListToArray {

  static void Main() {

    ArrayList al = new ArrayList();

    // Add elements to the array list.

    al.Add(1);

    al.Add(2);

    al.Add(3);

    al.Add(4);

    Console.Write("Contents: ");

    foreach(int i in al)

      Console.Write(i + " ");

    Console.WriteLine();

    // Get the array.

    int[] ia = (int[]) al.ToArray(typeof(int));

    int sum = 0;

    // Sum the array.

    for(int i=0; i

      sum += ia[i];

www.freepdf-books.com



762

 

P a r t   I I :  



E x p l o r i n g   t h e   C #   L i b r a r y

    Console.WriteLine("Sum is: " + sum);

  }

}

The output from the program is shown here:



Contents: 1 2 3 4

Sum is: 10

The program begins by creating a collection of integers. Next, 


Download 4,07 Mb.

Do'stlaringiz bilan baham:
1   ...   940   941   942   943   944   945   946   947   ...   1096




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish