c#中List<T>find使用示例
2011-07-11 16:32
676 查看
[title2]Delegates[/title2]
namespaceSystem{
publicdelegatevoidAction<T>(Tobj);
publicdelegateboolPredicate<T>(Tobj);
publicdelegateUConverter<T,U>(Tfrom);
publicdelegateintComparison<T>(Tx,Ty);
}
[title2]List<T>[/title2]
publicclassList<T>:…{
publicintFindIndex(Predicate<T>match);
publicintFindIndex(intindex,Predicate<T>match);
publicintFindIndex(intindex,intcount,Predicate<T>match);
publicintFindLastIndex(Predicate<T>match);
publicintFindLastIndex(intindex,Predicate<T>match);
publicintFindLastIndex(intindex,intcount,Predicate<T>match);
publicList<T>FindAll(Predicate<T>match);
publicTFind(Predicate<T>match);
publicTFindLast(Predicatematch);
publicboolExists(Predicate<T>match);
publicboolTrueForAll(Predicate<T>match);
publicintRemoveAll(Predicate<T>match);
publicvoidForEach(Action<T>action);
publicvoidSort(Comparison<T>comparison);
publicList<U>ConvertAll<U>(Converter<T,U>converter);
}
FindingEvenIntegersinList<T>
List<int>integers=newList<int>();For(inti=1;i<=10;i++)integers.Add(i);
List<int>even=integers.FindAll(delegate(inti){
returni%2==0;
});
FindingComplexTypeinList<T>
publicclassOrder{publicOrder(intnumber,stringitem){…}
publicintNumber{get{returnnumber;}}
publicstringItem{get{returnitem;}}
…
}
List<Order>orders=newList<Order>();
intorderNumber=10;
Orderorder=orders.Find(delegate(Ordero){
returno.Number==orderNumber;
});
ComputingSumofIntegersinList<T>
List<int>integers=newList<int>();for(inti=1;i<=10;i++)integers.Add(i);
intsum;
integers.ForEach(delegate(inti){sum+=i;});
SortOrdersinList<T>
List<Order>orders=newList<Order>();orders.Add(newOrder(10,”Milk”));
orders.Add(newOrder(5,”Cheese”));
orders.Sort(delegate(Orderx,Ordery){
returnComparer<int>.Default.Compare(x.Number,y.Number);
});
ConvertOrderstoOrderNumbers
List<Order>orders=newList<Order>();orders.Add(newOrder(10,”Milk”));
orders.Add(newOrder(5,”Cheese”));
List<int>numbers=orders.ConvertAll(delegate(Orderx){
returno.Number;
});
转自:
最近寫案子常常用到List<T>,這個東西還真好用
因為它有下列東西:
List<T>.Sort()→排序T
List<T>.Find()→找出一個T
List<T>.FindAll()→找出多個T
List<T>.Exist()→判斷T是否存在
小弟就寫個範例介紹這些東西吧..
GenericList.aspx
01 | <%@PageLanguage="C#"AutoEventWireup="true"CodeFile="GenericList.aspx.cs"Inherits="GenericList"%> |
02 |
03 | <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"" |
04 |
05 | < [b]html xmlns = " > |
06 | < head runat = "server" > |
07 | < title >GenericList</ title > |
08 | </ head > |
09 | < body > |
10 | < form id = "form1" runat = "server" > |
11 | < div > |
12 | 原始資料: |
13 | < asp:GridView ID = "GridView1" runat = "server" > |
14 | </ asp:GridView > |
15 | </ div > |
16 | </ form > |
17 | </ body > |
18 | </ html > |
001 | using System; |
002 | using System.Collections.Generic; |
003 | using System.Web; |
004 | using System.Web.UI; |
005 | using System.Web.UI.WebControls; |
006 |
007 | public partial class GenericList:System.Web.UI.Page |
008 | { |
009 |
010 | protected void Page_Load( object sender,EventArgse) |
011 | { |
012 | List<Person>lstPerson= new List<Person>(); |
013 | lstPerson.Add( new Person(1, "puma" ,10)); |
014 | lstPerson.Add( new Person(2, "F6Team" ,20)); |
015 | lstPerson.Add( new Person(3, "ASP.NET" ,30)); |
016 | lstPerson.Add( new Person(4, "Dotblogs" ,40)); |
017 |
018 | //原始資料顯示在GridView上 |
019 | this .GridView1.DataSource=lstPerson; |
020 | this .GridView1.DataBind(); |
021 |
022 |
023 |
024 | //List<T>.Find() |
025 | //找出Name='puma'的Person |
026 | Response.Write( "找出Name='puma'的Person→" ); |
027 | Response.Write(lstPerson.Find( delegate (Personp){ return p.Name== "puma" ;}).ToString()+ "<p>" ); |
028 |
029 |
030 |
031 | //List<T>.FindAll() |
032 | //找出Age>10的數目 |
033 | Response.Write( "找出Age>10的數目→" ); |
034 | Response.Write(lstPerson.FindAll( delegate (Personp){ return p.Age>10;}).Count.ToString()+ "<p>" ); |
035 |
036 |
037 |
038 | //List<T>.Exists() |
039 | //檢查Name='F6'是否存在 |
040 | Response.Write( "檢查Name='F6'是否存在→" ); |
041 | Response.Write(lstPerson.Exists( delegate (Personp){ return p.Name== "F6" ;}).ToString()+ "<p>" ); |
042 |
043 |
044 |
045 | //List<T>.Sort() |
046 | //依Name升冪排序 |
047 | Response.Write( "<p>依Name升冪排序↑<br/>" ); |
048 | lstPerson.Sort( delegate (Personp1,Personp2){ return Comparer< string >.Default.Compare(p1.Name,p2.Name);}); |
049 | foreach (Personp in lstPerson) |
050 | { |
051 | Response.Write(p.ToString()+ "<br/>" ); |
052 | } |
053 |
054 |
055 |
056 | //List<T>.Sort() |
057 | //依Name降冪排序 |
058 | Response.Write( "<p>依Name降冪排序↓<br/>" ); |
059 | lstPerson.Sort( delegate (Personp1,Personp2){ return Comparer< string >.Default.Compare(p2.Name,p1.Name);}); |
060 | foreach (Personp in lstPerson) |
061 | { |
062 | Response.Write(p.ToString()+ "<br/>" ); |
063 | } |
064 | } |
065 | } |
066 |
067 | public class Person |
068 | { |
069 | private int _ID; |
070 | private string _Name; |
071 | private int _Age; |
072 |
073 | public Person( int ID, string Name, int Age) |
074 | { |
075 | _ID=ID; |
076 | _Name=Name; |
077 | _Age=Age; |
078 | } |
079 |
080 | public int ID |
081 | { |
082 | set {_ID=value;} |
083 | get { return _ID;} |
084 | } |
085 |
086 | public string Name |
087 | { |
088 | set {_Name=value;} |
089 | get { return _Name;} |
090 | } |
091 |
092 | public int Age |
093 | { |
094 | set {_Age=value;} |
095 | get { return _Age;} |
096 | } |
097 |
098 | public override string ToString() |
099 | { |
100 | return string .Format( "ID:{0},Name:{1},Age:{2}" ,_ID,_Name,_Age); |
101 | } |
102 | } |
[/b]转自微软官方:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Xml.Linq;
namespaceFind
{
classProgram
{
privatestaticstringIDtoFind="bk109";
privatestaticList<Book>Books=newList<Book>();
publicstaticvoidMain(string[]args)
{
FillList();
//FindabookbyitsID.
Bookresult=Books.Find(
delegate(Bookbk)
{
returnbk.ID==IDtoFind;
}
);
if(result!=null)
{
DisplayResult(result,"FindbyID:"+IDtoFind);
}
else
{
Console.WriteLine("\nNotfound:{0}",IDtoFind);
}
//Findlastbookincollectionpublishedbefore2001.
result=Books.FindLast(
delegate(Bookbk)
{
DateTimeyear2001=newDateTime(2001,01,01);
returnbk.Publish_date<year2001;
});
if(result!=null)
{
DisplayResult(result,"Lastbookincollectionpublishedbefore2001:");
}
else
{
Console.WriteLine("\nNotfound:{0}",IDtoFind);
}
//Findallcomputerbooks.
List<Book>results=Books.FindAll(FindComputer);
if(results!=null)
{
DisplayResults(results,"Allcomputer:");
}
else
{
Console.WriteLine("\nNobooksfound.");
}
//Findallbooksunder$10.00.
results=Books.FindAll(
delegate(Bookbk)
{
returnbk.Price<10.00;
}
);
if(results!=null)
{
DisplayResults(results,"Booksunder$10:");
}
else
{
Console.WriteLine("\nNobooksfound.");
}
//Findindexvalues.
Console.WriteLine();
intndx=Books.FindIndex(FindComputer);
Console.WriteLine("Indexoffirstcomputerbook:{0}",ndx);
ndx=Books.FindLastIndex(FindComputer);
Console.WriteLine("Indexoflastcomputerbook:{0}",ndx);
intmid=Books.Count/2;
ndx=Books.FindIndex(mid,mid,FindComputer);
Console.WriteLine("Indexoffirstcomputerbookinthesecondhalfofthecollection:{0}",ndx);
ndx=Books.FindLastIndex(Books.Count-1,mid,FindComputer);
Console.WriteLine("Indexoflastcomputerbookinthesecondhalfofthecollection:{0}",ndx);
}
//Populatesthelistwithsampledata.
privatestaticvoidFillList()
{
//CreateXMLelementsfromasourcefile.
XElementxTree=XElement.Load(@"c:\temp\books.xml");
//Createanenumerablecollectionoftheelements.
IEnumerable<XElement>elements=xTree.Elements();
//Evaluateeachelementandsetsetvaluesinthebookobject.
foreach(XElementelinelements)
{
Bookbook=newBook();
book.ID=el.Attribute("id").Value;
IEnumerable<XElement>props=el.Elements();
foreach(XElementpinprops)
{
if(p.Name.ToString().ToLower()=="author")
{
book.Author=p.Value;
}
elseif(p.Name.ToString().ToLower()=="title")
{
book.Title=p.Value;
}
elseif(p.Name.ToString().ToLower()=="genre")
{
book.Genre=p.Value;
}
elseif(p.Name.ToString().ToLower()=="price")
{
book.Price=Convert.ToDouble(p.Value);
}
elseif(p.Name.ToString().ToLower()=="publish_date")
{
book.Publish_date=Convert.ToDateTime(p.Value);
}
elseif(p.Name.ToString().ToLower()=="description")
{
book.Description=p.Value;
}
}
Books.Add(book);
}
DisplayResults(Books,"Allbooks:");
}
//Explicitpredicatedelegate.
privatestaticboolFindComputer(Bookbk)
{
if(bk.Genre=="Computer")
{
returntrue;
}
{
returnfalse;
}
}
privatestaticvoidDisplayResult(Bookresult,stringtitle)
{
Console.WriteLine();
Console.WriteLine(title);
Console.WriteLine("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}",result.ID,
result.Author,result.Title,result.Genre,result.Price,
result.Publish_date.ToShortDateString());
Console.WriteLine();
}
privatestaticvoidDisplayResults(List<Book>results,stringtitle)
{
Console.WriteLine();
Console.WriteLine(title);
foreach(Bookbinresults)
{
Console.Write("\n{0}\t{1}\t{2}\t{3}\t{4}\t{5}",b.ID,
b.Author,b.Title,b.Genre,b.Price,
b.Publish_date.ToShortDateString());
}
Console.WriteLine();
}
}
publicclassBook
{
publicstringID{get;set;}
publicstringAuthor{get;set;}
publicstringTitle{get;set;}
publicstringGenre{get;set;}
publicdoublePrice{get;set;}
publicDateTimePublish_date{get;set;}
publicstringDescription{get;set;}
}
}
if($!=jQuery){
$=jQuery.noConflict();
}
varisLogined=true;
varcb_blogId=56535;
varcb_entryId=1760987;
varcb_blogApp="yuanyuan";
varcb_blogUserGuid="7019a4a2-0545-de11-9510-001cf0cd104b";
varcb_entryCreatedDate='2010/6/1917:39:00';
相关文章推荐
- 【转载】[C#/ASP.NET]List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- [C#/ASP.NET]List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- [C#/ASP.NET]List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- [C#/ASP.NET]List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- [C#/ASP.NET]List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- C#中的List<string>泛型类示例
- List<T>的Sort,Find,Exists等的使用(摘抄)
- ASP.NET List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- C# List<T>的嵌套和foreach的使用
- C#中使用BindingList 绑定DataGridView 可以实现动态绑定,优与List<T>集合的绑定
- 深入理解 c# 第一章 使用IComparer<Product>委托 对 List <Product> 进行排序
- C#:泛型集合—List<T>使用技巧
- List<>中Sort()、Find()、FindAll()、Exist()的使用方法
- C#学习日记2016-12-22 关于List<T>的使用和说明
- 深入理解 c# 第一章 使用扩展方法对 List<Product> 排序
- 如何使用<Beginning ASP.NET 3.5 in C# and VB>书中的示例代码
- C#中的List<string>泛型类示例
- [C#]泛型与非泛型集合类的区别及使用例程,包括ArrayList,Hashtable,List<T>,Dictionary<Tkey,Tvalue>,SortedList<Tkey,Tvalue>,Queue<T>,Stack<T>等
- C# - 使用 List<> 泛型给GridView控件数据
- C# List<T>使用方式