您的位置:首页 > 理论基础 > 数据结构算法

最全数据结构详述: List VS IEnumerable VS IQueryable VS ICollection VS IDictionary

2015-11-06 11:35 459 查看
本文对常用的数据结构详述:Array,ArrayList,List,IList,ICollection,Stack,Queue,HashTable,Dictionary,IQueryable,IEnumerable。



Collection(集合)

Collection是数据记录集合,

编写代码过程中,常常需要合适的容器保存临时数据,方便修改和查找,如何选取合适的数据容器,关键在于将执行的数据操作以及数据记录是否大量。



Array(数组)

特征

1.固定大小,数组的大小是初始化时决定无法修改的数值。

2.强类型,存储数据元素类型必须在初始化时指定,因此在运行时,不需要耗费额外的时间来定义数组类型,能够大大提升运行效率。

3.可使用Foreach关键字实现数组迭代和查找。

因为数组大小是固定的,且是强类型数据结构,因此在运行时只占用很少的内存,运行时效率很高。



//ItisobviousthatstrArrayis

[code]//1.string-->StronglyType
//2.Sized=10-->FixedSize


string[]strArray=newstring[10];


for(inti=0;i<10;i++)

{

if(strArray[i]==null)

{

strArray[i]=(i+1).ToString();

}

}


this.ListBoxArray.DataSource=null;

this.ListBoxArray.Items.Clear();


this.ListBoxArray.DataSource=strArray;

this.ListBoxArray.DataBind();

[/code]

ArrayList

1.ArrayList没有固定的长度,容量可动态增加,可应用于开发人员无法确定数组元素个数等场景,当然这种情况下,在定义结构体的时候会非常耗时。

2.ArrayList不是强类型,ArrayList中不同元素类型可以不相同,并且需要在运行时根据实际的输入来确定元素类型。因此在运行时消耗内存较多。

3.可使用Froeach关键字操作ArrayList。





publicclassProduct

[code]{
publicProduct()

{


}

publicProduct(stringCode,stringName)

{

_Code=Code;

_Name=Name;

}


publicstring_Code{get;set;}

publicstring_Name{get;set;}

}

[/code]

ArrayList支持String,int,以及十进制小数类型。


//ItisNOTobviousthatstrArrayListis1.string?int?object?decimal?-->NOTStronglyType

[code]//2.Sized=10?20?100?-->NOTFixedSize
//Namespace:System.Collections


System.Collections.ArrayListstrArrayList=newSystem.Collections.ArrayList();

//System.Linq.IQueryabletypeofdataisnotspecificruntimedeferedsupport

strArrayList.Add("Mahsa");//"Mahsa":isstring

strArrayList.Add(1);//1:isinteger

strArrayList.Add(0.89);//0.89:isdecimal


this.ListBoxArrayList.DataSource=null;

this.ListBoxArrayList.Items.Clear();

this.ListBoxArrayList.DataSource=strArrayList;

this.ListBoxArrayList.DataBind();


System.Text.StringBuilderstr=newSystem.Text.StringBuilder();


foreach(variteminstrArrayList)

{

str.Append(","+item);

}

this.lblArrayList.Text=str.ToString();


//Belowisoldwaytofillobjfromproduct,inArraylistyouneedtocreatemorethanoneinstance

//ProductobjProduct=newProduct();

//objProduct.Code="1001";

//objProduct.Name="Chair";


//ItisNOTobviousthatstrArrayListis

//1.string?int?object?decimal?OROBJECT??-->NOTStronglyType

//2.Sized=10?20?100?-->NOTFixedSize

//Namespace:System.Collections


System.Collections.ArrayListobjArrayList=newSystem.Collections.ArrayList();


objArrayList.Add(newProduct("1001","Chair"));

objArrayList.Add(newProduct("1002","Sofa"));

objArrayList.Add(newProduct("1003","Carpet"));


this.DropDownListArrayListObject.DataSource=null;

this.DropDownListArrayListObject.Items.Clear();

this.DropDownListArrayListObject.DataSource=objArrayList;


//*FindingamongObjectofArrayListisdifficult,youhavetofindyourspecificitembyindex

ProductobjTemp=(Product)objArrayList[0];

objArrayList.Remove(objTemp);

//*

this.DropDownListArrayListObject.DataTextField="_Name";

this.DropDownListArrayListObject.DataValueField="_Code";

this.DropDownListArrayListObject.DataBind();

this.GridViewArrayListObject.DataSource=objArrayList;

this.GridViewArrayListObject.DataBind();

[/code]

HashTable(哈希表)

HashTable是一种定义关键字的数据结构体,使用哈希表查找数据非常方便,哈希表既不是强类型也不固定大小限制。




//ItisNOTobviousthatstrArrayListis

[code]//1.string?int?object?decimal?OROBJECT??-->NOTStronglyType
//2.Sized=10?20?100?-->NOTFixedSize

//Namespace:System.Collections

//HashtablesolvetheprobleminArraylistwhenwearelookingforspecificitem

//Hashtablededicateakeyforeachitem,thenfindingitemiseasierandfaster


System.Collections.HashtableobjHashTable=newSystem.Collections.Hashtable();


objHashTable.Add("1001","Chair");

objHashTable.Add("1002","Sofa");

objHashTable.Add("1003","Carpet");



this.DropDownListHashTable.DataSource=null;

this.DropDownListHashTable.Items.Clear();

this.DropDownListHashTable.DataSource=objHashTable;

//*findingitemiseasieryoujustneedtopointtoitbycallitskey

objHashTable.Remove("1002");

//*

this.DropDownListHashTable.DataTextField="Value";

this.DropDownListHashTable.DataValueField="Key";

this.DropDownListHashTable.DataBind();

[/code]

Stack

栈是最典型的数据结构,栈具有优先级划分的数据结构,栈为每个内容项定义优先级,表示每个Item入栈和出栈的优先顺序。因此操作栈中的数据,需要先将数据push到栈的顶部,需要删除元素必须变成栈顶部,即要遵守后进先出(LIFO)的原则。

栈与哈希表一样既不是强类型也不限制元素个数。



Push操作


//StackisLIFO:LastinFirstOut

[code]System.Collections.StackobjStackPush=newSystem.Collections.Stack();

//ByPushmethodyoucaninsertitematthetopofthestack

objStackPush.Push("Mahsa");

objStackPush.Push("Hassankashi");

this.lblPop.Text="";

this.ListBoxStack.DataSource=objStackPush.ToArray();

this.ListBoxStack.DataBind();

[/code]

Pop操作


System.Collections.StackobjStackPop=newSystem.Collections.Stack();

[code]
objStackPop.Push("Mahsa");

objStackPop.Push("Hassankashi");


//ByPopmethodyoucanremoveitemfromthetopofthestack-->LastinFirstin

this.lblPop.Text=objStackPop.Pop().ToString();


this.ListBoxStack.DataSource=objStackPop.ToArray();

this.ListBoxStack.DataBind();

[/code]

Queue

Queue同栈一样也是具有优先级定义的结构体,遵循的规则是先进先出(FIFO),既不是强类型也不具有固定的大小限制。



入队操作


//QueueisFIFO:FirstinFirstOut

[code]System.Collections.QueueobjQueue=newSystem.Collections.Queue();

//ByEnqueuemethodyoucaninsertitemattheENDoftheQueue

objQueue.Enqueue("Mahsa");

objQueue.Enqueue("Hassankashi");

objQueue.Enqueue("Cosmic");

objQueue.Enqueue("Verse");


this.lblQueue.Text="";

this.ListBoxQueue.DataSource=objQueue.ToArray();

this.ListBoxQueue.DataBind();


出队操作

[/code]


System.Collections.QueueobjQueue=newSystem.Collections.Queue();

[code]
objQueue.Enqueue("Mahsa");

objQueue.Enqueue("Hassankashi");

objQueue.Enqueue("Cosmic");

objQueue.Enqueue("Verse");


//ByDequeuemethodyoucanremoveitemfromtheBEGININGoftheQueue-->FirstinFirstoutFIFO

this.lblQueue.Text=objQueue.Dequeue().ToString();


this.ListBoxQueue.DataSource=objQueue.ToArray();

this.ListBoxQueue.DataBind();

[/code]

入队操作


System.Collections.QueueobjQueue=newSystem.Collections.Queue();

[code]
objQueue.Enqueue("Mahsa");

objQueue.Enqueue("Hassankashi");

objQueue.Enqueue("Cosmic");

objQueue.Enqueue("Verse");


//ByDequeuemethodyoucanremoveitemfromtheBEGININGoftheQueue-->FirstinFirstoutFIFO

this.lblQueue.Text=objQueue.Dequeue().ToString();


this.ListBoxQueue.DataSource=objQueue.ToArray();

this.ListBoxQueue.DataBind();

[/code]

List

什么情况下需要使用List?

1.List长度可不固定

2.当数据为通用类型,List是强类型,List中元素类型不需要等到运行时来确定,这种特性使得List运行时效率非常高。

3.可使用Foreach关键字。

因为List不需要设定固定的大小,List灵活度高,且效率高常用于开发过程中。




//LikeArrayisStrongType

[code]//LikeArrayListwithNoDimension
System.Collections.Generic.List<string>strList=newList<string>();



strList.Add("Mahsa");

strList.Add("Hassankashi");

strList.Add("Cosmic");

strList.Add("Verse");


this.ListBoxListGeneric.DataSource=strList;

this.ListBoxListGeneric.DataBind();


System.Text.StringBuilderstr=newSystem.Text.StringBuilder();


foreach(variteminstrList)

{

str.Append(","+item);

}

this.lblList.Text=str.ToString();

[/code]

IList

IList继承了List,包含多种方法的List接口。如果你无法判断代码改动的可能性,可以使用IList接口,减少模块之间的依赖性。IList是接口因此无法被实例化,所以必须使用List来初始化。


System.Collections.Generic.IList<string>strIList=newList<string>();



我们一起了解一下具体的类和接口之间的区别。

1.具体类可继承其他类,并实现一个或多个接口。

2.在内部类中可以定义变量并赋值,接口中不允许此操作。

3.具体类可包含构造函数,而接口中不能定义构造函数

4.抽象类中可包含访问修饰符如public,private等,接口中不能包含。




//IlistcannotbeinstantiatefromIlist,soitshouldbeinstantiatefromList

[code]System.Collections.Generic.IList<string>strIList=newList<string>();

strIList.Add("Mahsa");

strIList.Add("Hassankashi");

strIList.Add("Cosmic");

strIList.Add("Verse");



this.ListBoxListGeneric.DataSource=strIList;

this.ListBoxListGeneric.DataBind();


System.Text.StringBuilderstr=newSystem.Text.StringBuilder();


foreach(variteminstrIList)

{

str.Append(","+item);

}

this.lblList.Text=str.ToString();

[/code]

IEnumerable

IEnumerable常用于遍历集合元素,但是无法修改(删除或添加)数据,使用IEnumberable会从服务器端将所有数据拷贝到客户端,并进行一定的过滤,如果服务器端有大量数据会造成内存负载超重。




//IEnumerablecannotbeinstantiatefromEnumerable,soitshouldbeinstantiatefromList

[code]System.Collections.Generic.IEnumerable<Employee>empIEnumerable=newList<Employee>
{newEmployee{ID=1001,Name="Mahsa"},

newEmployee{ID=1002,Name="Hassankashi"},

newEmployee{ID=1003,Name="CosmicVerse"},

newEmployee{ID=1004,Name="Technical"}

};



this.GridViewIEnumerable.DataSource=empIEnumerable;

this.GridViewIEnumerable.DataBind();


System.Text.StringBuilderstr=newSystem.Text.StringBuilder();


foreach(EmployeeiteminempIEnumerable)

{

str.Append(","+item.ID+"-"+item.Name);

}


this.lblIEnumerable.Text=str.ToString();

[/code]

IQueryable

IQueryable与IEnumberable不同的是,当从服务器端加载过量的数据,IQueryable会自动减少应用负载。IQueryable可保证大数据量时应用程序的高性能。

IQueryable会先过滤数据,然后发送给客户端。




DataAccessEntitiesctx=newDataAccessEntities();

[code]varctx=newDataAccessEntities();
[/code]




//DifferencebetweenIQueryableandIEnumerable

[code]
//YoucaninstantiateIEnumerablefromList


IEnumerable<employee>queryIEnumerable=newList<employee>();



//BringALLrecordsfromserver-->toclientthenfiltercollection

//Tobringalldatafromserveryoushouldomitwhereclusefromlinqtosql

queryIEnumerable=fromminctx.Employeesselectm;


//IfyouusewhereasextensionmethodwithIEnumerablethenAllrecordswillbeloaded

queryIEnumerable=queryIEnumerable.Where(x=>x.ID==1).ToList();




//YoucannotinstantiateIQueryable


IQueryable<employee>queryIQueryable=null;


//BringjustONErecordfromserver-->toclient


queryIQueryable=(fromminctx.Employees

wherem.ID==1

selectm);


//WheneveryoucallIQueryableso==>Itwillbeexecuted

this.GridViewIQueryable.DataSource=queryIQueryable.ToList();

this.GridViewIQueryable.DataBind();

</employee>

[/code]

SQLProfiler:

如何追踪查询语句生成TSQL,生成需要的数据结构体:

Step1:
Start->MSSQLServer2008->PerformanceTools->SQLServerProfiler




Step2:
SQLServerProfiler->File->NewTrace



Step3:
输入连接数据库的用户名和密码



Step4:
General(Tab)->UsetheTemplate:Standard



Step5:
EventSelection(Tab)->Event:TSQL->Select:SQL-BatchCompleted|SelectShowallColumns

PressColumnFilter->DatabaseName:Like:"DataAccess"

运行



Step6:
查看结果



Step7:
生成IEnumerable数据:


SELECT

[code][Extent1].[ID]AS[ID],
[Extent1].[Name]AS[Name],

[Extent1].[Age]AS[Age]

FROM[dbo].[Employee]AS[Extent1]

[/code]



生成IQueryable:

SELECT
[Extent1].[ID]AS[ID],
[Extent1].[Name]AS[Name],
[Extent1].[Age]AS[Age]
FROM[dbo].[Employee]AS[Extent1]
WHERE1=[Extent1].[ID]




ICollection继承了IEnumberable,但是IEnumberable是基于索引的,ICollection不基于索引。




//IList{indexerandModify}vsICollection{randomlyandModify}

[code]//CollectioncannotbeinstantiatefromICollection,soitshouldbeinstantiatefromList
System.Collections.Generic.ICollection<string>strICollection=newList<string>();

strICollection.Add("Mahsa");

strICollection.Add("Hassankashi");


//Countable***

intICollectionCount=strICollection.Count;


this.ListBoxICollection.DataSource=strICollection;

this.ListBoxICollection.DataBind();

System.Text.StringBuilderstr=newSystem.Text.StringBuilder();

foreach(variteminstrICollection)

{

str.Append(","+item);

}

this.lblICollection.Text=str.ToString();


//IList***

System.Collections.Generic.IList<Employee>objIList=newList<Employee>();

objIList=(fromminctx.Employees

selectm).ToList();


Employeeobj=objIList.Where(i=>i.Name=="Sara").FirstOrDefault();

intindexofSara=objIList.IndexOf(obj);

intcIList=objIList.Count;


//ICollection***

System.Collections.Generic.ICollection<Employee>objICollection=newList<Employee>();

objICollection=(fromminctx.Employees

selectm).ToList();

EmployeeobjIC=objICollection.Where(i=>i.Name=="Sara").FirstOrDefault();

//Youcannotgetindexofobject,ifyouclearcommentfrombelowcodeappearserror

//intindexofSaraICollection=objIC.IndexOf(objIC);

intcICollection=objICollection.Count;

[/code]

StackGeneric

入栈:


//StackisLIFO:LastinFirstOut

[code]//HereisforPushStackinGeneric
//System.Collections.StackobjStackPush=newSystem.Collections.Stack();

//Stack<T>canbeinstantiatedfromStack<T>


System.Collections.Generic.Stack<int>objStackPush=newSystem.Collections.Generic.Stack<int>();


objStackPush.Push(1);

objStackPush.Push(2);


this.lblPopGeneric.Text="";

this.ListBoxStackGeneric.DataSource=objStackPush.ToArray();

this.ListBoxStackGeneric.DataBind();

[/code]

出栈:


//StackisLIFO:LastinFirstOut

[code]//HereisforPopStackinGeneric
//System.Collections.StackobjStackPop=newSystem.Collections.Stack();

//Stack<T>canbeinstantiatedfromStack<T>


System.Collections.Generic.Stack<int>objStackPop=newSystem.Collections.Generic.Stack<int>();


objStackPop.Push(1);

objStackPop.Push(2);


this.lblPop.Text=objStackPop.Pop().ToString();

this.ListBoxStack.DataSource=objStackPop.ToArray();

this.ListBoxStack.DataBind();

[/code]

QueueGeneric

入队:


//QueueisFIFO:FirstinFirstOut

[code]//HereisforEnqueueQueueinGeneric
//System.Collections.QueueobjQueue=newSystem.Collections.Queue();

//Queue<T>canbeinstantiatedfromQueue<T>


System.Collections.Generic.Queue<int>objQueue=newSystem.Collections.Generic.Queue<int>();

objQueue.Enqueue(1);

objQueue.Enqueue(2);


this.lblQueue.Text="";


this.ListBoxQueue.DataSource=objQueue.ToArray();

this.ListBoxQueue.DataBind();

[/code]

出队:


//QueueisFIFO:FirstinFirstOut

[code]//HereisforEnqueueQueueinGeneric
//System.Collections.QueueobjQueue=newSystem.Collections.Queue();

//Queue<T>canbeinstantiatedfromQueue<T>


System.Collections.Generic.Queue<int>objQueue=newSystem.Collections.Generic.Queue<int>();

objQueue.Enqueue(1);

objQueue.Enqueue(2);


this.lblQueue.Text="";


this.ListBoxQueue.DataSource=objQueue.ToArray();

this.ListBoxQueue.DataBind();

[/code]

Dictionary及IDictionary:

Dictionary可通用,而哈希表不是通用的。Dictionary定义<TKey,Tvalue>。IDictionary是Dictionary的接口,如果在后期开发中需要大量修改,建议使用IDictionary。

//DictionarycaninstantiatefromDictionary,DictionaryissimilartoHashtable,
//DictionaryisGENERICbutHashtableisNONGENERIC
//SuchHashtableyoucanfindobjectbyitskey
System.Collections.Generic.Dictionary<int,string="">objDictionary=newDictionary<int,string="">();

objDictionary.Add(1001,"Mahsa");
objDictionary.Add(1002,"Hassankashi");
objDictionary.Add(1003,"Cosmicverse");

stringstr=objDictionary[1002];

this.ListBoxDictionary.DataSource=objDictionary;
this.ListBoxDictionary.DataBind();</int,>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: