c# 数组中找元素 元素存在.docx

上传人:b****5 文档编号:7263994 上传时间:2023-01-22 格式:DOCX 页数:14 大小:19.94KB
下载 相关 举报
c# 数组中找元素 元素存在.docx_第1页
第1页 / 共14页
c# 数组中找元素 元素存在.docx_第2页
第2页 / 共14页
c# 数组中找元素 元素存在.docx_第3页
第3页 / 共14页
c# 数组中找元素 元素存在.docx_第4页
第4页 / 共14页
c# 数组中找元素 元素存在.docx_第5页
第5页 / 共14页
点击查看更多>>
下载资源
资源描述

c# 数组中找元素 元素存在.docx

《c# 数组中找元素 元素存在.docx》由会员分享,可在线阅读,更多相关《c# 数组中找元素 元素存在.docx(14页珍藏版)》请在冰豆网上搜索。

c# 数组中找元素 元素存在.docx

c#数组中找元素元素存在

数组中找元素

1.Array.Exists方法

.NETFramework4

∙.NETFramework4.5

∙.NETFramework3.5

∙.NETFramework3.0

∙.NETFramework2.0

确定指定数组包含的元素是否与指定谓词定义的条件匹配。

命名空间:

System

程序集:

mscorlib(在mscorlib.dll中)

语法

C#

C++

F#

VB

复制

publicstaticboolExists

T[]array,

Predicatematch

类型参数

T

数组元素的类型。

参数

array

类型:

T[]

要搜索的从零开始的一维Array。

match

类型:

System.Predicate

Predicate,定义要搜索的元素的条件。

返回值

类型:

System.Boolean

如果array包含一个或多个元素与指定谓词定义的条件匹配,则为true;否则为false。

异常

异常

条件

ArgumentNullException

array为null。

-或-

match为null。

备注

Predicate是对方法的委托,如果传递给它的对象与委托中定义的条件匹配,则该方法返回true。

array的元素被逐个传递给Predicate,找到一个匹配项时处理就会停止。

此方法的运算复杂度为O(n),其中n是array的Length。

示例

下面的代码示例演示Exists泛型方法和使用Predicate泛型委托的其他几种泛型方法。

创建一个包含8个恐龙名称的字符串数组,其中有2个名称(分别位于位置1和5)以“saurus”结尾。

该代码示例还定义了一个名为EndsWithSaurus的搜索谓词方法,该方法接受一个字符串作为参数,并返回一个布尔值,指示输入的字符串是否以“saurus”结尾。

Exists方法在预测方法为其返回true的第一个元素(在本例中为“Amargasaurus”)处停止并返回true。

注意

在C#和VisualBasic中,不必显式创建Predicate委托(在VisualBasic中为Predicate(OfString))。

这些语言会通过上下文推知正确的委托,并自动创建委托。

TrueForAll泛型方法在预测方法为其返回false的第一个元素处停止并返回false。

Find泛型方法从开始处遍历数组,依次将每个元素传递给EndsWithSaurus方法。

当EndsWithSaurus方法对元素“Amargasaurus”返回true时,搜索停止。

使用FindLast泛型方法从末尾处向后搜索数组。

它在位置5处找到元素"Dilophosaurus"。

FindAll泛型方法用于返回包含以"saurus"结尾的所有元素的数组。

显示这些元素。

C#

C++

VB

复制

usingSystem;

publicclassDinoDiscoverySet

{

publicstaticvoidMain()

{

string[]dinosaurs=

{

"Compsognathus","Amargasaurus","Oviraptor",

"Velociraptor","Deinonychus","Dilophosaurus",

"Gallimimus","Triceratops"

};

DinoDiscoverySetGoMesozoic=newDinoDiscoverySet(dinosaurs);

GoMesozoic.DiscoverAll();

GoMesozoic.DiscoverByEnding("saurus");

}

privatestring[]dinosaurs;

publicDinoDiscoverySet(string[]items)

{

dinosaurs=items;

}

publicvoidDiscoverAll()

{

Console.WriteLine();

foreach(stringdinosaurindinosaurs)

{

Console.WriteLine(dinosaur);

}

}

publicvoidDiscoverByEnding(stringEnding)

{

PredicatedinoType;

switch(Ending.ToLower())

{

case"raptor":

dinoType=EndsWithRaptor;

break;

case"tops":

dinoType=EndsWithTops;

break;

case"saurus":

default:

dinoType=EndsWithSaurus;

break;

}

Console.WriteLine(

"\nArray.Exists(dinosaurs,\"{0}\"):

{1}",

Ending,

Array.Exists(dinosaurs,dinoType));

Console.WriteLine(

"\nArray.TrueForAll(dinosaurs,\"{0}\"):

{1}",

Ending,

Array.TrueForAll(dinosaurs,dinoType));

Console.WriteLine(

"\nArray.Find(dinosaurs,\"{0}\"):

{1}",

Ending,

Array.Find(dinosaurs,dinoType));

Console.WriteLine(

"\nArray.FindLast(dinosaurs,\"{0}\"):

{1}",

Ending,

Array.FindLast(dinosaurs,dinoType));

Console.WriteLine(

"\nArray.FindAll(dinosaurs,\"{0}\"):

",Ending);

string[]subArray=

Array.FindAll(dinosaurs,dinoType);

foreach(stringdinosaurinsubArray)

{

Console.WriteLine(dinosaur);

}

}

//Searchpredicatereturnstrueifastringendsin"saurus".

privateboolEndsWithSaurus(strings)

{

if((s.Length>5)&&

(s.Substring(s.Length-6).ToLower()=="saurus"))

{

returntrue;

}

else

{

returnfalse;

}

}

//Searchpredicatereturnstrueifastringendsin"raptor".

privateboolEndsWithRaptor(Strings)

{

if((s.Length>5)&&

(s.Substring(s.Length-6).ToLower()=="raptor"))

{

returntrue;

}

else

{

returnfalse;

}

}

//Searchpredicatereturnstrueifastringendsin"tops".

privateboolEndsWithTops(Strings)

{

if((s.Length>3)&&

(s.Substring(s.Length-4).ToLower()=="tops"))

{

returntrue;

}

else

{

returnfalse;

}

}

}

/*Thiscodeexampleproducesthefollowingoutput:

Compsognathus

Amargasaurus

Oviraptor

Velociraptor

Deinonychus

Dilophosaurus

Gallimimus

Triceratops

Array.Exists(dinosaurs,"saurus"):

True

Array.TrueForAll(dinosaurs,"saurus"):

False

Array.Find(dinosaurs,"saurus"):

Amargasaurus

Array.FindLast(dinosaurs,"saurus"):

Dilophosaurus

Array.FindAll(dinosaurs,"saurus"):

Amargasaurus

Dilophosaurus

*/

 

2.Array.Find方法

.NETFramework4.5

其他版本

命名空间:

System

程序集:

mscorlib(在mscorlib.dll中)

语法

C#

C++

F#

VB

复制

publicstaticTFind

T[]array,

Predicatematch

类型参数

T

数组元素的类型。

参数

array

类型:

T[]

要搜索的从零开始的一维Array。

match

类型:

System.Predicate

Predicate,定义要搜索的元素的条件。

返回值

类型:

T

如果找到与指定谓词定义的条件匹配的第一个元素,则为该元素;否则为类型T的默认值。

异常

异常

条件

ArgumentNullException

array为null。

-或-

match为null。

备注

Predicate是对方法的委托,如果传递给它的对象与委托中定义的条件匹配,则该方法返回true。

array的元素被逐个传递给Predicate,在Array中向前移动,从第一个元素开始,到最后一个元素结束。

当找到匹配项时处理即停止。

此方法的运算复杂度为O(n),其中n是array的Length。

示例

下面的代码示例将Predicate委托与Find泛型方法一起使用以搜索Point结构的数组。

如果X和Y字段的产品大于100,000,则该代理所代表的方法ProductGT10将返回true。

Find方法调用数组的每个元素的代理,从而在第一个满足测试条件的点返回。

说明

VisualBasic和C#用户不需要显式创建委托,也不需要指定泛型方法的类型参数。

编译器会根据您提供的方法参数确定必需的类型。

C#

VB

复制

usingSystem;

usingSystem.Drawing;

publicclassExample

{

publicstaticvoidMain()

{

//CreateanarrayoffivePointstructures.

Point[]points={newPoint(100,200),

newPoint(150,250),newPoint(250,375),

newPoint(275,395),newPoint(295,450)};

//TofindthefirstPointstructureforwhichXtimesY

//isgreaterthan100000,passthearrayandadelegate

//thatrepresentstheProductGT10methodtothestatic

//FindmethodoftheArrayclass.

Pointfirst=Array.Find(points,ProductGT10);

//Notethatyoudonotneedtocreatethedelegate

//explicitly,ortospecifythetypeparameterofthe

//genericmethod,becausetheC#compilerhasenough

//contexttodeterminethatinformationforyou.

//Displaythefirststructurefound.

Console.WriteLine("Found:

X={0},Y={1}",first.X,first.Y);

}

//ThismethodimplementsthetestconditionfortheFind

//method.

privatestaticboolProductGT10(Pointp)

{

if(p.X*p.Y>100000)

{

returntrue;

}

else

{

returnfalse;

}

}

}

/*Thiscodeexampleproducesthefollowingoutput:

Found:

X=275,Y=395

*/

3.Array.IndexOf方法(Array,Object)

.NETFramework4.5

∙.NETFramework4

∙.NETFramework3.5

∙.NETFramework3.0

∙.NETFramework2.0

搜索指定的对象,并返回整个一维Array中第一个匹配项的索引。

命名空间:

System

程序集:

mscorlib(在mscorlib.dll中)

语法

C#

C++

F#

VB

复制

publicstaticintIndexOf(

Arrayarray,

Objectvalue

参数

array

类型:

System.Array

要搜索的一维Array。

value

类型:

System.Object

要在array中查找的对象。

返回值

类型:

System.Int32

如果在整个array中找到value的匹配项,则为第一个匹配项的索引;否则为该数组的下限减1。

异常

异常

条件

ArgumentNullException

array为null。

RankException

array是多维的。

备注

向前搜索一维Array,从第一个元素开始,到最后一个元素结束。

使用Object.Equals方法,将元素与指定的值进行比较。

如果元素类型是非内部(用户定义)类型,则使用该类型的Equals实现。

由于大多数数组以零作为下限,在找不到value时,此方法通常将返回-1。

在极少数情况下,数组的下限等于Int32.MinValue,且找不到value,这时此方法返回Int32.MaxValue,即System.Int32.MinValue-1。

此方法的运算复杂度为O(n),其中n是array的Length。

在.NETFramework2.0版中,此方法使用Array的Equals和CompareTo方法来确定由value参数指定的Object是否存在。

在早期版本的.NETFramework中,这是通过使用Equals和valueObject本身的CompareTo方法来确定的。

示例

下面的代码示例显示如何确定指定元素的第一个匹配项的索引。

C#

C++

VB

复制

usingSystem;

publicclassSamplesArray{

publicstaticvoidMain(){

//CreatesandinitializesanewArraywiththreeelementsofthesamevalue.

ArraymyArray=Array.CreateInstance(typeof(String),12);

myArray.SetValue("the",0);

myArray.SetValue("quick",1);

myArray.SetValue("brown",2);

myArray.SetValue("fox",3);

myArray.SetValue("jumps",4);

myArray.SetValue("over",5);

myArray.SetValue("the",6);

myArray.SetValue("lazy",7);

myArray.SetValue("dog",8);

myArray.SetValue("in",9);

myArray.SetValue("the",10);

myArray.SetValue("barn",11);

//DisplaysthevaluesoftheArray.

Console.WriteLine("TheArraycontainsthefollowingvalues:

");

PrintIndexAndValues(myArray);

//Searchesforthefirstoccurrenceoftheduplicatedvalue.

StringmyString="the";

intmyIndex=Array.IndexOf(myArray,myString);

Console.WriteLine("Thefirstoccurrenceof\"{0}\"isatindex{1}.",myString,myIndex);

//SearchesforthefirstoccurrenceoftheduplicatedvalueinthelastsectionoftheArray.

myIndex=Array.IndexOf(myArray,myString,4);

Console.WriteLine("Thefirstoccurrenceof\"{0}\"betweenindex4andtheendisatindex{1}.",myString,myIndex);

//SearchesforthefirstoccurrenceoftheduplicatedvalueinasectionoftheArray.

myIndex=Array.IndexOf(myArray,myString,6,5);

Console.WriteLine("Thefirstoccurrenceof\"{0}\"betweenindex6andindex10isatindex{1}.",myString,myIndex);

}

publicstaticvoidPrintIndexAndValues(ArraymyArray){

for(inti=myArray.GetLowerBound(0);i<=myArray.GetUpperBound(0);i++)

Console.WriteLine("\t[{0}]:

\t{1}",i,myArray.GetValue(i));

}

}

/*

Thiscodeproducesthefollowingoutput.

TheArraycontainsthefollowingvalues:

[0]:

the

[1]:

quick

[2]:

brown

[3]:

fox

[4]:

jumps

[5]:

over

[6]:

the

[7]:

lazy

[8]:

dog

[9]:

in

[10]:

the

[11]:

barn

Thefirstoccurrenceof"the"isatindex0.

Thefirstoccurrenceof"the"betweenindex4andtheendisatindex6.

Thefirstoccurrenceof"the"betweenindex6andindex10isatindex6.

*/

版本信息

.NETFramework

受以下版本支持:

4.5、4、3.5、3.0、2.0、1.1、1.0

.NETFrameworkClientProfile

受以下版本支持:

4、3.5SP1

可移植类库

受以下版本支持:

可移植类库

适用于Windows应用商店应用的.NET

受以下版本支持:

Windows8

平台

Windows8,WindowsServer2012,Windows7,WindowsVistaSP2,WindowsServer2008(不支持服务器核心角色),WindowsServer2008R2(支持带SP1或更高版本的服务器核心角色;不支持Itanium)

.NETFramework并不是对每个平台的所有版本都提供支持。

有关支持的版本的列表,请参见.NETFramework系统要求。

请参见

参考

Array类

IndexOf重载

System命名空间

LastIndexOf

其他资源

 

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1