Tuesday, August 12, 2008

Sorting and Searching in Generic List


Many times I have come across sorting a list or searching an object from list.
Here I am putting those code blocks that can help us to do so....

Sorting

List persons = PopulatePersonList();
//Sort A-Z
persons.Sort(delegate(Person x, Person y)
{
return x.Name.CompareTo(y.Name);
});

For Z-A sorting, we should use,
return y.Name.CompareTo(x.Name);


Searching

List persons = PopulatePersonList();
Person p =
persons.Find(delegate(Person x)
{
if (x.Name == "abc")
return true;
else
return false;
});

The above delegate implementation can also be replaced with static function call as shown below.

List persons = PopulatePersonList();
Person p = persons.Find(IsPersonInList);

private static bool IsPersonInList(Person x)
{
if(x.Name == "abc")
return true;
else
return false;
}

Yep ! That's It...

Happy Coding__

No comments: