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);
}
}
Url: http://www.jonasjohn.de/snippets/csharp/lists-and-delegates.htm
Language: C# | User: ShareMySnippets | Created: Oct 16, 2013