Си шарп методы для массивов

Массивы (Руководство по программированию на C#)

В структуре данных массива можно хранить несколько переменных одного типа. Чтобы объявить массив, следует указать тип его элементов. Если требуется, чтобы массив мог хранить элементы любого типа, можно указать object в качестве его типа. В унифицированной системе типов C# все типы, стандартные и определяемые пользователем, ссылочные типы и типы значений напрямую или косвенно наследуются из Object.

Пример

В следующих примерах создаются одномерные массивы, многомерные массивы и массивы массивов:

class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > > 

Общие сведения о массивах

Массив имеет следующие свойства:

  • Массив может быть одномерным, многомерным или массивом массивов.
  • Количество измерений и длина каждого из измерений задаются, когда создается экземпляр массива. Эти значения нельзя изменить во время существования экземпляра.
  • Используемые по умолчанию значения числовых элементов массива равны нулю, и элементам ссылки присвоено значение null .
  • В массиве массивов элементы являются ссылочными типами и инициализируются значением null .
  • Массивы индексируются от нуля: массив с n элементами индексируется от 0 до n-1 .
  • Элементы массива могут иметь любой тип, в том числе тип массива.
  • Типы массивов — это ссылочные типы, производные от абстрактного базового типа . Все массивы реализуют IList и IEnumerable. Для итерации по массиву можно использовать оператор foreach. Одномерные массивы также реализуют IList и IEnumerable .

Поведение значения по умолчанию

  • Для типов значений элементы массива инициализируются со значением по умолчанию — шаблоном с нулевыми битами; элементы будут иметь значение .
  • Все ссылочные типы (в том числе не допускающие значения NULL) имеют значения .
  • Для типов, допускающих значения NULL, параметр HasValue имеет значение false , а для элементов будет установлено значение null .

Массивы как объекты

В C# массивы представляют собой реальные объекты, а не просто адресуемые области непрерывной памяти, как в C и C++. Array — это абстрактный базовый тип для всех типов массивов. Вы можете использовать свойства и другие члены класса, входящие в Array. Например, с помощью свойства Length можно получить длину массива. В следующем коде значение длины массива numbers ( 5 ) присваивается переменной с именем lengthOfNumbers :

int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length; 

В классе Array представлено множество других полезных методов и свойств для сортировки, поиска и копирования массивов. В следующем примере свойство Rank используется для отображения количества измерений массива.

class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions. 

См. также раздел

Дополнительные сведения см. в спецификации языка C#. Спецификация языка является предписывающим источником информации о синтаксисе и использовании языка C#.

Читайте также:  Шрифт

Источник

Arrays (C# Programming Guide)

You can store multiple variables of the same type in an array data structure. You declare an array by specifying the type of its elements. If you want the array to store elements of any type, you can specify object as its type. In the unified type system of C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object.

Example

The following example creates single-dimensional, multidimensional, and jagged arrays:

class TestArraysClass < static void Main() < // Declare a single-dimensional array of 5 integers. int[] array1 = new int[5]; // Declare and set array element values. int[] array2 = new int[] < 1, 3, 5, 7, 9 >; // Alternative syntax. int[] array3 = < 1, 2, 3, 4, 5, 6 >; // Declare a two dimensional array. int[,] multiDimensionalArray1 = new int[2, 3]; // Declare and set array element values. int[,] multiDimensionalArray2 = < < 1, 2, 3 >, < 4, 5, 6 >>; // Declare a jagged array. int[][] jaggedArray = new int[6][]; // Set the values of the first array in the jagged array structure. jaggedArray[0] = new int[4] < 1, 2, 3, 4 >; > > 

Array overview

An array has the following properties:

  • An array can be single-dimensional, multidimensional or jagged.
  • The number of dimensions and the length of each dimension are established when the array instance is created. These values can’t be changed during the lifetime of the instance.
  • The default values of numeric array elements are set to zero, and reference elements are set to null .
  • A jagged array is an array of arrays, and therefore its elements are reference types and are initialized to null .
  • Arrays are zero indexed: an array with n elements is indexed from 0 to n-1 .
  • Array elements can be of any type, including an array type.
  • Array types are reference types derived from the abstract base type Array. All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array. Single-dimensional arrays also implement IList and IEnumerable .

Default value behaviour

  • For value types, the array elements are initialized with the default value, the 0-bit pattern; the elements will have the value 0 .
  • All the reference types (including the non-nullable), have the values null .
  • For nullable value types, HasValue is set to false and the elements would be set to null .

Arrays as Objects

In C#, arrays are actually objects, and not just addressable regions of contiguous memory as in C and C++. Array is the abstract base type of all array types. You can use the properties and other class members that Array has. An example of this is using the Length property to get the length of an array. The following code assigns the length of the numbers array, which is 5 , to a variable called lengthOfNumbers :

int[] numbers = < 1, 2, 3, 4, 5 >; int lengthOfNumbers = numbers.Length; 

The Array class provides many other useful methods and properties for sorting, searching, and copying arrays. The following example uses the Rank property to display the number of dimensions of an array.

class TestArraysClass < static void Main() < // Declare and initialize an array. int[,] theArray = new int[5, 10]; System.Console.WriteLine("The array has dimensions.", theArray.Rank); > > // Output: The array has 2 dimensions. 

See also

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

Читайте также:  Php pear для opencart

Источник

Си шарп методы для массивов

Все массивы в C# построены на основе класса Array из пространства имен System. Этот класс определяет ряд свойств и методов, которые мы можем использовать при работе с массивами. Основные свойства и методы:

  • Свойство Length возвращает длину массива
  • Свойство Rank возвращает размерность массива
  • int BinarySearch (Array array, object? value) выполняет бинарный поиск в отсортированном массиве и возвращает индекс найденного элемента
  • void Clear (Array array) очищает массив, устанавливая для всех его элементов значение по умолчанию
  • void Copy (Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length) копирует из массива sourceArray начиная с индекс sourceIndex length элементов в массив destinationArray начиная с индекса destinationIndex
  • bool Exists (T[] array, Predicate match) проверяет, содержит ли массив array элементы, которые удовлеворяют условию делегата match
  • void Fill (T[] array, T value) заполняет массив array значением value
  • T? Find (T[] array, Predicate match) находит первый элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
  • T? FindLast (T[] array, Predicate match) находит последний элемент, который удовлеворяет определенному условию из делегата match. Если элемент не найден, то возвращается null
  • int FindIndex (T[] array, Predicate match) возвращает индекс первого вхождения элемента, который удовлеворяет определенному условию делегата match
  • int FindLastIndex (T[] array, Predicate match) возвращает индекс последнего вхождения элемента, который удовлеворяет определенному условию
  • T[] FindAll (T[] array, Predicate match) возвращает все элементы в виде массива, которые удовлеворяет определенному условию из делегата match
  • int IndexOf (Array array, object? value) возвращает индекс первого вхождения элемента в массив
  • int LastIndexOf (Array array, object? value) возвращает индекс последнего вхождения элемента в массив
  • void Resize (ref T[]? array, int newSize) изменяет размер одномерного массива
  • void Reverse (Array array) располагает элементы массива в обратном порядке
  • void Sort (Array array) сортирует элементы одномерного массива

Разберем самые используемые методы.

Поиск индекса элемента

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // находим индекс элемента "Bob" int bobIndex = Array.BinarySearch(people, "Bob"); // находим индекс первого элемента "Tom" int tomFirstIndex = Array.IndexOf(people, "Tom"); // находим индекс последнего элемента "Tom" int tomLastIndex = Array.LastIndexOf(people, "Tom"); // находим индекс первого элемента, у которого длина строки больше 3 int lengthFirstIndex = Array.FindIndex(people, person => person.Length > 3); // находим индекс последнего элемента, у которого длина строки больше 3 int lengthLastIndex = Array.FindLastIndex(people, person => person.Length > 3); Console.WriteLine($"bobIndex: "); // 2 Console.WriteLine($"tomFirstIndex: "); // 0 Console.WriteLine($"tomLastIndex: "); // 4 Console.WriteLine($"lengthFirstIndex: "); // 3 Console.WriteLine($"lengthLastIndex: "); // 5

Если элемент не найден в массиве, то методы возвращают -1.

Читайте также:  Python datetime to sql datetime

Поиск элемента по условию

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // находим первый и последний элементы // где длина строки больше 3 символов string? first = Array.Find(people, person => person.Length > 3); Console.WriteLine(first); // Kate string? last = Array.FindLast(people, person => person.Length > 3); Console.WriteLine(last); // Alice // находим элементы, у которых длина строки равна 3 string[] group = Array.FindAll(people, person => person.Length == 3); foreach (var person in group) Console.WriteLine(person); // Tom Sam Bob Tom

Изменение порядка элементов массива

Например, изменим порядок элементов:

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; Array.Reverse(people); foreach (var person in people) Console.Write($" "); // "Alice", "Tom", "Kate", "Bob", "Sam", "Tom"

Также можно изменить порядок только части элементов:

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // изменяем порядок 3 элементов начиная c индекса 1 Array.Reverse(people, 1, 3); foreach (var person in people) Console.Write($" "); // "Tom", "Kate", "Bob", "Sam", "Tom", "Alice"

В данном случае изменяем порядок только 3 элементов начиная c индекса 1.

Изменение размера массива

Для изменения размера массива применяется метод Resize. Его первый параметр — изменяемый массив, а второй параметр — количество элементов, которые должны быть в массиве. Если второй параметр меньше длины массива, то массив усекается. Если значение параметра, наоборот, больше, то массив дополняется дополнительными элементами, которые имеют значение по умолчанию. Причем первый параметр передается по ссылке:

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // уменьшим массив до 4 элементов Array.Resize(ref people, 4); foreach (var person in people) Console.Write($" "); // "Tom", "Sam", "Bob", "Kate"

Копирование массива

Метод Copy копирует часть одного массива в другой:

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; var employees = new string[3]; // копируем 3 элемента из массива people c индекса 1 // и вставляем их в массив employees начиная с индекса 0 Array.Copy(people,1, employees,0, 3); foreach (var person in employees) Console.Write($" "); // Sam Bob Kate

В данном случае копируем 3 элемента из массива people начиная c индекса 1 и вставляем их в массив employees начиная с индекса 0.

Сортировка массива

Отсортируем массив с помощью метода Sort() :

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; Array.Sort(people); foreach (var person in people) Console.Write($" "); // Alice Bob Kate Sam Tom Tom

Этот метод имеет много перегрузок. Например, одна из версий позволяет отсортировать только часть массива:

var people = new string[] < "Tom", "Sam", "Bob", "Kate", "Tom", "Alice" >; // сортируем с 1 индекса 3 элемента Array.Sort(people, 1, 3); foreach (var person in people) Console.Write($" "); // Tom Bob Kate Sam Tom Alice

Источник

Оцените статью