List<>中Find的用法小結(jié)
I've been looking for help on how to find objects in Generics with List.Find() method .... and ... take a look what I have found.
In the follow example, I created a simple class:
public class Person
{
private int _id;
private string _name;
public int ID { get{ return _id;} set{ _id = value;}}
public int Name { get{ return _name;} set{ _name= value;}}
public Person(int id, string name)
{
_id = id;
_name = name;
}
}
In the example, there's a simple class with two private attributes. Now we're going to create a typed List of this object and take advantage of the Find() method
public void CreateAndSearchList()
{
//create and fill the collection
List<Person> myList = new List<Person>();
myList.Add(new Person(1, "AndreySanches"));
myList.Add(new Person(2, "AlexandreTarifa"));
myList.Add(new Person(3, "EmersonFacunte"));
//find a specific object
Person myLocatedObject = myList.Find(delegate(Person p) {return p.ID == 1; });
}
備注:在list和array集合中搜索元素經(jīng)常使用該方法,主要技術(shù)是泛型委托
list用法注意:如果增加一個對象,必須重新new一個對象,看下面的例子:
person p=new pewson();
for(int i=0;i<5;i++)
{
p.ID=i;
p.Name="xxxx";
list.add(p);
}
for(int i=0;i<5;i++)
{
person p=new person();
p.ID=i;
p.Name="xxxx";
list.add(p);
}
上面有區(qū)別嗎?在輸出list的值是有區(qū)別了,第一個list里面存放的都是一樣的,結(jié)果和最后一個一樣,都是同一個人對象,第二個list達(dá)到預(yù)期的效果,存儲不同的人對象。這是為什么?原因很簡單,一個list對象中存儲的都是對一個共有的對象進(jìn)行引用,所以以最后改變的值為準(zhǔn)。
對象的排序:本文主要闡述對存儲datatable的list進(jìn)行按TableName排序
1、新建一個sort類
public class SceneSort:IComparer<DataTable>
{
public int Compare(DataTable obj1, DataTable obj2)
{
int tableNameLength1;
int tableNameLength2;
if (obj1 == null)
{
if (obj2 == null)
return 0;
else
return -1;
}
else
{
if (obj2 == null)
return 1;
else
{
tableNameLength1=obj1.TableName.Length;
tableNameLength2=obj2.TableName.Length;
if (Convert.ToInt32(obj1.TableName.Substring(2,tableNameLength1-2))>Convert.ToInt32(obj2.TableName.Substring(2,tableNameLength2-2)))
return 1; //大于返回1
else if (Convert.ToInt32(obj1.TableName.Substring(2,tableNameLength1-2))<Convert.ToInt32(obj2.TableName.Substring(2,tableNameLength2-2)))
return -1; //小于返回-1
else
return 0; //相等返回0
}
}
}
2 排序:
List<DataTable> ldt = new List<DataTable>();
SceneSort ss=new SceneSort ();
tablelist.sort(ss);即可對list進(jìn)行排序;
相關(guān)文章
C#實現(xiàn)Quartz任務(wù)調(diào)度的示例代碼
使用 Quartz.NET,你可以很容易地安排任務(wù)在應(yīng)用程序啟動時運(yùn)行,或者每天、每周、每月的特定時間運(yùn)行,甚至可以基于更復(fù)雜的調(diào)度規(guī)則,本文給大家介紹了C#實現(xiàn)Quartz任務(wù)調(diào)度,需要的朋友可以參考下2024-04-04
C#實現(xiàn)在Form里面內(nèi)嵌dos窗體的方法
這篇文章主要介紹了C#實現(xiàn)在Form里面內(nèi)嵌dos窗體的方法,涉及C#針對Form窗體的設(shè)置及使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09
C#網(wǎng)絡(luò)爬蟲代碼分享 C#簡單的爬取工具
這篇文章主要為大家詳細(xì)介紹了C#網(wǎng)絡(luò)爬蟲代碼,教大家如何制作了簡單的爬取工具,感興趣的小伙伴們可以參考一下2016-07-07
C#中調(diào)用SAPI實現(xiàn)語音識別的2種方法
這篇文章主要介紹了C#中調(diào)用SAPI實現(xiàn)語音識別的2種方法,本文直接給出實現(xiàn)代碼,需要的朋友可以參考下2015-06-06

