欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-01-30 09:01:44
c#学习笔记- 浅谈数组复制,排序,取段,元组 using system; using system.collections.generic; names...

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#学习笔记- 浅谈数组复制,排序,取段,元组就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。