Saturday, February 23, 2008

Searching and Sorting a Generic List

If some of you are using arraylists or generic lists and are finding it difficult to search or sort a list for a Specific property value in the object, then below is a simple piece of code that uses anonymous delegates to accomplish this.


Example: Say you have a List with type object

public class Person

{

private string firstname;

private string lastname;

public string FirstName{get{return firstname;} set {firstname=value;}}

public string LastName{get{return lasttname;} set {lastname=value;}}


public Person()

{


}


}

// usage
List pl = new List();
// add items
pl.Add(new Person(){FirstName="Fred",LastName="Besterwitch"});
pl.Add(new Person(){FirstName="Eric",LastName="Johnson"});
pl.Add(new Person(){FirstName="Eric",LastName="Clapton"});
pl.Add(new Person(){FirstName="Mark",LastName="knophler"});
pl.Add(new Person(){FirstName="Carlos",LastName="Santana"});


string Searchfor="Santana";

Person person = (Person)pl.Find(
delegate(Person p)
{ return p.LastName.Trim().ToUpper().Equals(Searchfor.Trim().ToUpper());
}
);



No comments: