欢迎来到入门教程网!

C#教程

当前位置:主页 > 软件编程 > C#教程 >

C#学习笔记- 浅谈数组复制,排序,取段,元组

来源:本站原创|时间:2020-01-10|栏目:C#教程|点击:

C#学习笔记- 浅谈数组复制,排序,取段,元组

using System;
using System.Collections.Generic;

namespace Application
{
class Test
{
static void Main ()
{

//元组类型Tuple是静态类型,用静态方法创建实例,超过8个元素则第8个元素是元组类型

var tupe = Tuple.Create<int,int,string,string> (1, 2, "a", "b");
Console.WriteLine ("{ 0},{ 1}",tupe.Item1, tupe.Item3);


//=====Array类是抽象类,只能通过它的静态方法CreateInstance()创建实例

//=====如果事先不知道类型,可以用此方法

Array arrays = Array.CreateInstance (typeof(int), 5);
for (int i = 0; i < arrays.Length; i++) {
arrays.SetValue (35, i);
Console.WriteLine (arrays.GetValue (i));
}


Person[] persons = {
new Person { firstName = "su", lastName = "uifu" },
new Person { firstName = "chen", lastName = "xaohua" },
new Person { firstName = "cbb", lastName = "ruifu" },
new Person { firstName = "utt", lastName = "xiaohua" }
} ;

//=====Clone()复制数组,引用类型复制索引值,值类型复制值

Person[] persons1 = persons.Clone ();
Array.Sort (persons, new PersonComparer (PersonCompareType.lastName));
foreach (var p in persons) {
Console.WriteLine (p);
}

//======ArraySegment<T>对数组取段====
var segments = new ArraySegment<Person> (persons, 1, 2);
for (int i = segments.Offset; i < segments.Offset + segments.Count; i++) {
Console.WriteLine (segments.Array [i]);
}
}

public class Person
{
public string firstName{ get; set; }
public string lastName{ get; set; }

public override string ToString ()
{
return String.Format ("{ 0},{ 1}", firstName, lastName);
}
}
//======要对引用类型的数组使用Array.sort()方法,必须对类实现IComparable<T>接口

//======或写一个附加类并实现Comparer<T>接口
public enum PersonCompareType
{
firstName,
lastName
}

public class PersonComparer:IComparer<Person>
{
private PersonCompareType pct;

public PersonComparer (PersonCompareType pct)
{
this.pct = pct;
}
public int Compare(Person x,Person y)
{
if (x == null)
throw new ArgumentNullException ();
if (y == null)
throw new ArgumentNullException ();
switch (pct) {
case PersonCompareType.firstName:
return x.firstName.CompareTo (y.lastName);
case PersonCompareType.lastName:
return x.lastName.CompareTo (y.lastName);
default:
throw new ArgumentException ("no..");
}
}

}
}

以上这篇C#学习笔记- 浅谈数组复制,排序,取段,元组就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

上一篇:C#根据身份证号码判断出生日期和性别

栏    目:C#教程

下一篇:C#访问SQLServer增删改查代码实例

本文标题:C#学习笔记- 浅谈数组复制,排序,取段,元组

本文地址:https://www.xiuzhanwang.com/a1/C_jiaocheng/6284.html

网页制作CMS教程网络编程软件编程脚本语言数据库服务器

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:835971066 | 邮箱:835971066#qq.com(#换成@)

Copyright © 2002-2020 脚本教程网 版权所有