List<>中Find的用法小结
本文导语: 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; publi...
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 myList = new List();
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集合中搜索元素经常使用该方法,主要技术是泛型委托
list用法注意:如果增加一个对象,必须重新new一个对象,看下面的例子:
person p=new pewson();
for(int i=0;i