First: In the. net1.1, I also have a lot of programmers like me, will be used to ArrayList, at that time to find this collection element, most of the use for loop to complete, of course, can also use the BinarySearch method. But since there are net2.0 and. net3.5, ArrayList has rarely been used, and everyone thinks that list<t> is superior to ArrayList in performance. Now that you have List<t>, with LINQ, queries for list<t> collections are no longer single. Here are three ways to do this: they work together to find elements that have a number greater than 50000 in a collection of person.
The person class is defined as follows:
public class Person
{
public string firstName
{ get; set; }
public string lastName
{ get; set; }
public int ID
{ get; set; }
}
Constructs a generic collection of person first. Of course, there is generally no such large set, but it is necessary to compare the search performance of different methods.
Code
List<Person> list = new List<Person>();
for (int i = 0; i < 100001; i++)
{
Person p = new Person();
p.firstName = i.ToString() + "firstName";
p.lastName = i.ToString() + "lastName";
p.ID = i;
list.Add(p);
}
1:list<t> provides a findall way.
Code
public class FindPerson
{
public string firstName;
public FindPerson(string _firstName)
{ this.firstName = _firstName; }
public bool PersonPredicate(Person p)
{
return p.ID >= 50000;
}
}
Stopwatch sw = new Stopwatch();
sw.Start();
List<Person> persons = list.FindAll(new Predicate<Person>(fp.PersonPredicate));
sw.Stop();
Response.Write("Find方法搜索用时" + sw.ElapsedMilliseconds.ToString() + "<br/>");