Three methods of searching a generic collection of objects


In usual programming it is often needed to searh a collection of objects. People adapt different methods to complete this task. Here I am showing three different methods of searching a generic collection containing objects.



public class Person
{
private string _Name;
private string _Phone;
private string _Address;

public string Name
{
get
{
return _Name;
}
}

public string Phone
{
get
{
return _Phone;
}
}

public string Address
{
get
{
return _Address;
}
}

public Person(string name, string phone, string address)
{
_Name = name;
_Phone = phone;
_Address = address;
}
}



Private void ListSearchingMethods ()
{

List<Person> PersonList = new List<Person>();

PersonList.Add(new Person("Farhan", "111-111-1134", "El Segundo, 90245"));
PersonList.Add(new Person("Haroon", "222-222-2234", "Gardena, 90345"));
PersonList.Add(new Person("Mansoor", "444-223-2343", "Aberdeen, 33434"));
PersonList.Add(new Person("Imran", "444-223-2343", "Gardena, 90451"));


// Method1: Use find method of the List<> Collection.
Person ObjF = PersonList.Find(delegate(Person p) { return p.Name == "Farhan"; });


// Method2: Use Linq to query the collection
var Query = from p in PersonList
where p.Name == "Mansoor"
select p;

Person ObjQ;
if (Query.Count<Person>() > 0)
ObjQ = Query.First();


// Method3: Use iteration
Person ObjL;
foreach (Person p in PersonList)
{
if (p.Name == "Haroon")
{
ObjL = p;
break;
}
}

}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: