Array Methods - II

C# Array Methods

In our previous topic, we talked about methods that are related to arrays and called with the Array class. On this page, we will give examples of methods used without specifying the Array class.

Average( ) Method

It is a method that returns the double type by calculating the average of all the elements of a numeric array. Sample:

int[ ] numbers = { 1,2,3,4,5,6,7 };
 
double avg = numbers.Average();
 
label1.Text = avg.ToString();

 

Sum( ) Method

Adds the values ​​of all the elements of the array.

int sum = array1.Sum();

 

Concat( ) Method

Allows merging of two directories. In the example below, the elements of array1 are also added to the elements of array2 and converted to array type with the ToArray() method. The resulting new sequence is called the lastSequence.

int[ ] array1= { 1,2,3,4,5,6,7 };
int[ ] array2={8,9,10,11,12};
int[ ] finalArray= array1.Concat(array2).ToArray();

 

Contains( ) Method

It allows searching for the desired value in an array. Returns True if the searched value is found, False if not found. Sample:

int[] numbers = { 1,2,3,4,5,6,7 };
 
int a = int.Parse(textBox1.Text);
 
if (numbers.Contains(a)) label1.Text = "Found";
else label1.Text = "Not Found";

 

CopyTo( ) Method

It is used to copy the entire contents of one directory to another directory. Usage;

sourceArrayName . CopyTo ( targetArrayName, startIndexNo);

Here, the startIndexNo determines from which element the paste operation will be made in the target array.

int[ ] array1 = { 1, 2, 3, 4, 5 };
 
int[ ] array2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
array1.CopyTo(array2, 3);

In this example, we have said to copy array1 and paste into array2, starting from element 3.

The number of elements of the target array does not change when the CopyTo method is used. That is, the elements of array1 are replaced with the corresponding elements in array2.

After the codes are running, the new version of array2 will be:

1, 2, 3, 1, 2, 3, 4, 5, 9, 10

An error will occur if the target string is not long enough. For example, we cannot copy array2 into array1. Likewise, the initial index number must be suitable for placing all the elements of the copied array.

 

Max( ) and Min( ) Methods

It is used to find the element with the largest (max) or smallest (min) value among the array elements.

label1.Text = array1.Max().ToString();

label1.Text = array1.Min().ToString();

 

SequenceEqual( ) Method

All elements of two sequences by comparing the same directory If true, it returns a different value is False.

if ( array1.SequenceEqual(array2) ) 

label1.Text = "Series Same";

 

Sum( ) Method

Adds the values ​​of all the elements of the array.

int sum = array1.Sum();

 

c# array methods, searching in array, averaging array, finding sum of array elements, copy array, copy array items

EXERCISES

There are no examples related to this subject.



COMMENTS




Read 840 times.

Online Users: 504



aray-methods