首页 > 其他分享 >.NET教程 - 数组(Array)

.NET教程 - 数组(Array)

时间:2022-09-29 08:11:46浏览次数:47  
标签:教程 string int public item 数组 Array NET

更新记录
转载请注明出处:
2022年9月29日 发布。
2022年9月28日 从笔记迁移到博客。

System.Array

说明

Array类型是所有一维和多维数组的基类

System.Array类型实现了IList接口、IList接口、ICollection接口、IEnumerable接口

注意:如果需要大小可以变化的类型,考虑使用List

数组都是System.Array类的实例

数组类型(Types of Arrays)

  1. Single dimensional array
  2. Multi-dimensional array

the multi-dimensional arrays are of two types

  1. Jagged array: Whose rows and columns are not equal
  2. Rectangular array: Whose rows and columns are equal

数组的长度和秩(Length and Rank)

可以使用以下数组实例方法和属性来获得数组的长度和秩

public int GetLength (int dimension);
public long GetLongLength (int dimension);
public int Length { get; }
public long LongLength { get; }
public int GetLowerBound (int dimension);
public int GetUpperBound (int dimension);
public int Rank { get; } // Returns number of dimensions in array

数组查询(Array Searching)

数组支持以下查询:

二分查找(BinarySearch methods)

For rapidly searching a sorted array for a particular item

查找索引(IndexOf/LastIndex methods)

For searching unsorted arrays for a particular item

查找元素(Find/FindLast/FindIndex/FindLastIndex/FindAll/Exists/TrueForAll)

For searching unsorted arrays for item(s) that satisfy a given Predicate

说明:一般情况下,没有查找到元素不会抛出异常,会返回-1/Null

数组查找

Array类型注意

注意:

数值的二分查找(binary search)只能在已经排序的数组上执行

数值的二分查找方法还可以接受IComparer or IComparer接口实现自定义排序

使用Array.Find方法+方法 查找元素

static void Main()
{
  string[] names = { "Rodney", "Jack", "Jill" };
  string match = Array.Find (names, ContainsA);
  Console.WriteLine (match);     // Jack
}
static bool ContainsA (string name) { return name.Contains ("a"); }

使用Array.Find方法+匿名方法 查找元素

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, delegate (string name)
                                    { return name.Contains ("a"); } );

使用Array.Find方法+Lambda表达式 查找元素

string[] names = { "Rodney", "Jack", "Jill" };
string match = Array.Find (names, n => n.Contains ("a"));     // Jack

数组排序(Sorting)

数组排序的主要方法:

// For sorting a single array:
public static void Sort<T> (T[] array);
public static void Sort    (Array array);
// For sorting a pair of arrays:
public static void Sort<TKey,TValue> (TKey[] keys, TValue[] items);
public static void Sort              (Array keys, Array items);

int index                 // Starting index at which to begin sorting
int length                // Number of elements to sort
IComparer<T> comparer     // Object making ordering decisions
Comparison<T> comparison  // Delegate making ordering decisions

实例:最简单的排序

int[] numbers = { 3, 2, 1 };
Array.Sort (numbers);                     // Array is now { 1, 2, 3 }

实例:以第一个数组的下标来排序第二个数组

int[] numbers = { 3, 2, 1 };
string[] words = { "three", "two", "one" };
Array.Sort (numbers, words);
// numbers array is now { 1, 2, 3 }
// words   array is now { "one", "two", "three" }

实例:将奇数排在前面

int[] numbers = { 1, 2, 3, 4, 5 };
Array.Sort (numbers, (x, y) => x % 2 == y % 2 ? 0 : x % 2 == 1 ? -1 : 1);
// numbers array is now { 1, 3, 5, 2, 4 }

数组反序(Reversing Elements)

预定义静态方法

public static void Reverse (Array array);
public static void Reverse (Array array, int index, int length);

实例:全部元素进行倒序

string[] pandaTest = new string[] { "Panda666", "Dog222" };
Array.Reverse(pandaTest);
foreach (string item in pandaTest)
{
    Console.WriteLine(item);
}

实例:部分元素进行倒序

string[] pandaTest = new string[] { "Test1", "Test2", "Test3" };
Array.Reverse(pandaTest, 1, 2);
foreach (string item in pandaTest)
{
    Console.WriteLine(item);
}

数组复制(Copying)

主要有4个方法:

实例方法:

Clone, CopyTo

静态方法:

Copy, ConstrainedCopy

说明:ConstrainedCopy表示要么复制全部成功,要么回滚

实例:原子复制数组

string[] pandaTest = new string[] { "Panda666" };
string[] des = new string[1];
Array.ConstrainedCopy(pandaTest, 0, des, 0, pandaTest.Length);

foreach (string item in des)
{
    Console.WriteLine(item);
}

转为不可变类型(只读类型)

使用Array.AsReadonly()方法

实例:使用Array.AsReadonly()方法

using System.Collections.ObjectModel;
string[] pandaTest = new string[] { "Panda666" };
ReadOnlyCollection<string> readOnlyCollection = Array.AsReadOnly(pandaTest);
foreach (string item in readOnlyCollection)
{
    Console.WriteLine(item);
}

数组转换和大小调整(Converting and Resizing)

数组转换:

使用Array.ConvertAll方法进行数组类型转换

使用LINQ进行数组类型转换

数组大小:

使用Resize方法进行数组大小转换

实例:使用Array.ConvertAll进行数组类型转换

float[] reals = { 1.3f, 1.5f, 1.8f };
int[] wholes = Array.ConvertAll (reals, r => Convert.ToInt32 (r));
// wholes array is { 1, 2, 2 }

实例:使用LINQ进行类型转换

string[] pandaTest = new string[] { "Panda" };
var result = from item in pandaTest
                select item[0];
foreach (char item in result)
{
    Console.WriteLine(item);
}

实例:使用Resize进行数组大小转换

string[] pandaTest = new string[] { "panda666" };
Array.Resize(ref pandaTest, 666);
//输出长度
Console.WriteLine(pandaTest.Count()); //666

实例

动态创建数组

Array a = Array.CreateInstance(typeof(string), 2);
a.SetValue("hi", 0); // → a[0] = "hi";
a.SetValue("there", 1); // → a[1] = "there";
string s = (string)a.GetValue(0); // → s = a[0];
//转为固定的数组
string[] cSharpArray = (string[])a;
string s2 = cSharpArray[0];

动态创建数组

Array instance = Array.CreateInstance(typeof(int),20);
//赋值
for (int i = 0; i < instance.Length; i++)
{
    instance.SetValue(i+1,i);
}

//读值
for (int i = 0; i < instance.Length; i++)
{
    Console.WriteLine(instance.GetValue(i));
}

//转为具体类型数组
int[] newArray = (int[])instance;

克隆数组(浅复制)

int[] arr = { 1, 2, 3, 4, 5};
//克隆
int[] newArr = (int[])arr.Clone();

克隆数组(浅复制)

string[] test1 = new string[3] { "Panda", "Dog", "Cat" };
string[] test2 = (string[])test1.Clone();
foreach (string item in test2)
{
    Console.WriteLine(item);
}

数组深拷贝(一层)

string[] test1 = new string[] { "Panda", "Cat", "Monkey" };
string[] test2 = new string[test1.Length];
for (int i = 0; i < test1.Length; i++)
{
    //检测是否值类型
    if (test1[i] is ValueType)
    {
        test2[i] = test1[i];
    }
    else
    {
        test2[i] = (string)test1[i].Clone();
    }
}
//修改Test2做测试
test2[0] = "Panda666";

foreach (string item in test2)
{
    Console.WriteLine(item);
}
Console.WriteLine("================================");

foreach (string item in test1)
{
    Console.WriteLine(item);
}

获得第一个元素和最后一个元素

int[] myArray = { 1, 2, 3 };
int first = myArray [0];
int last = myArray [myArray.Length - 1];

使用foreach遍历数组

int[] myArray = { 1, 2, 3 };
foreach (int val in myArray)
{
    Console.WriteLine (val);
}

使用Array.ForEach静态方法遍历数组

Array.ForEach (new[] { 1, 2, 3 }, Console.WriteLine);

数组排序

使用Array.Sort静态方法
注意:数组的元素必须实现IComparable接口
注意:预定义基本类型都已经实现了该接口
注意:Array.Sort静态方法使用QuickSort

using System;

namespace Test
{
    class PandaTest
    {
        public static void Main()
        {
            int[] arr = { 1, 3, 2, 4, 5};
            Array.Sort(arr);
            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }

            Console.ReadKey();
        }
    }
}

自定义排序

using System;

namespace Test
{
    /// <summary>
    /// 测试使用的员工类型
    /// </summary>
    class Employee:IComparable<Employee>
    {
        /// <summary>
        /// 工资,按工资从高到低排序
        /// </summary>
        public decimal Salary { get; set; }

        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }

        public Employee(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }

        /// <summary>
        /// 自定义排序
        /// </summary>
        /// <param name="other"></param>
        /// <returns></returns>
        public int CompareTo(Employee other)
        {
            if(this.Salary < other.Salary)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }

    class PandaTest
    {
        public static void Main()
        {
            Employee[] employees = 
            {
                new Employee("Panda",666),
                new Employee("Dog",888),
                new Employee("Cat",999)
            };

            Array.Sort(employees);

            foreach (var item in employees)
            {
                Console.WriteLine(item.Name + " " + item.Salary.ToString());
            }

            Console.ReadKey();
        }
    }
}

数组池

当应用经常创建和释放数组,可以使用数组池提高效率
ArrayPool

标签:教程,string,int,public,item,数组,Array,NET
From: https://www.cnblogs.com/cqpanda/p/16736859.html

相关文章

  • .NET教程 - 数值 & 随机数(Number & Random)
    更新记录转载请注明出处:2022年9月29日发布。2022年9月28日从笔记迁移到博客。System.Numerics.BigIntegerBigInteger说明BigInteger类型用于表示任意大的整数数......
  • 聊聊 dotnet 7 对 bool 与字符串互转的底层性能优化
    本文也叫跟着StephenToub大佬学性能优化系列。大家都知道在.NET7有众多的性能优化,其中就包括了对布尔和字符串互转的性能优化。在对布尔和字符串的转换的性能优化上......
  • kubenetes之pod
    创建一个基础的podvimnginx.yamlapiVersion:v1#必选,API的版本号kind:Pod#必选,类型Podmetadata:#必选,元数据name:nginx#必选,符合RFC1035规范的Pod......
  • 【教程】VsCodeForCPP 最简单一键启动VsCode C/C++环境,无需任何配置
    整合VsCode以前的教程中,总有各种同学由于环境变量编译器的配置问题出现无法使用的情况,于是我将VsCode移植成绿色版本,直接整合C++编译器,全部配置为动态路径,保证即开即用......
  • Python之telnetlib模块
    telnetlib是python标准库中的一员,我们可以使用该模块以telnet的方式与服务器交互。请观察下面示例了解它的用法:importtelnetlibdefrun_telnet(host,username,password,......
  • Oracle 11g安装教程(详细步骤)
    电脑装个Oracle装了三次,经历颇有点坎坷。主要这东西卸载也比较麻烦,卸载不干净重新安装还是有问题。参考了网上的一些资料,自己总结了一下。希望大家都能少猜一些坑吧!  ......
  • centos7 中iptables、firewalld 和 netfilter 的关系
    centos7系统使用firewalld服务替代了iptables服务,但是依然可以使用iptables来管理内核的netfilter但其实iptables服务和firewalld服务都不是真正的防火墙,只是用来定......
  • .NET 反向代理 YARP 代理 GRPC
    前面的YARP文档中,介绍了怎么去代理http,和如何根据域名转发,而在现在微服务的应用是越来越来多了,服务间的调用依靠http越来越不现实了,因为http多次握手的耗时越发......
  • CF1526E Oolimry and Suffix Array 组合数学
    看起来是后缀数组,但是看到求方案数就是dp,计数啥的了问满足后缀数组的字符串方案有多少观察样例,发现rk相邻的所在位置,字母要么是相等,要么是比其大大的话条件直接满足了,相......
  • dbeaver安装和使用教程
    文章目录​​一、简介​​​​二、安装教程​​​​三、使用教程​​​​1.连接MySQL数据库​​​​2.查看表数据​​​​3.查看表属性​​​​3.SQL编辑器和控制台​​......