Working with lists and delegates

Shows a simple example how to remove, modify and check items in lists by using delegates.

class Program
{
    static void Main(string[] args)
    {            
        //
        // Example list 
        //
        List<Person> Persons = new List<Person>();
 
        Persons.Add(new Person("Jonas", 22));
        Persons.Add(new Person("Peter", 19));
        Persons.Add(new Person("Daniel", 20));
        Persons.Add(new Person("Yvonne", 18));
        Persons.Add(new Person("Jana", 26));
 
 
        // Removes all persons younger than 20 years
        Persons.RemoveAll(delegate(Person P)
        {
            return (P.Age < 20);
        });
 
 
        // Searches for specific entries and returns a list of
        // them
        List<Person> NewList = Persons.FindAll(delegate(Person P)
        {
            return (P.Age > 25);
        });
 
        // Loops trough every item and modifies the
        // entries
        Persons.ForEach(delegate(Person P){
            P.Name = "<" + P.Name + ">";
        });
 
        // Returns true or false if a specific entry is found
        bool Contains = Persons.Exists(delegate(Person P)
        {
            return (P.Age > 25);
        });
 
 
        // Print the new list
        foreach (Person PersonObject in NewList)
            Console.WriteLine(PersonObject);
 
    }
}
 
// Example class
public class Person
{
    private string name = "";
    public string Name
    {
        get { return name;}
        set { name = value;}
    }
 
    private int age = 0;
    public int Age
    {
        get { return age; }
        set { age = value; }
    }	
 
    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="Name"></param>
    /// <param name="Age"></param>
    public Person(string Name, int Age)
    {
        this.name   = Name;
        this.age    = Age;
    }
 
    /// <summary>
    /// Overrides the default ToString method with
    /// a custom one
    /// </summary>
    /// <returns></returns>
    public override string ToString()
    {
        return String.Format("{0} ({1})", this.Name, this.Age);
    }
 
}
Snippet information

Author:
Jonas John

License:
Public domain

Language:
C#

Created:
08/13/2007

Updated:
08/13/2007

Tags:
, , ,




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

None.