// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections.Generic; using System.Linq; namespace E { public delegate void D(string msg); public class Standard { public event D ToDo; public void Test() { ToDo("Standard"); } } public class Custom { public List ToDo = new List(); public void Test() { ToDo.ForEach(d => d("Custom")); } } public class CustomWithFilter { private List> ToDo = new List>(); public void Add(string key, D d) { ToDo.Add(Tuple.Create(key, d)); } public void Test(string filter) { ToDo.Where(t => t.Item1==filter).ToList().ForEach(t => t.Item2("Custom with filter")); } } public class Map { private Dictionary> ToDo = new Dictionary>(); public void Add(string key, D d) { if(!ToDo.ContainsKey(key)) { ToDo.Add(key, new List()); } ToDo[key].Add(d); } public void Test(string filter) { ToDo[filter].ForEach(t => t("Map")); } } public class CustomWithFlexFilter { private List> ToDo = new List>(); public void Add(string key, D d) { ToDo.Add(Tuple.Create(key, d)); } public void Test(Func f) { ToDo.Where(t => f(t.Item1)).ToList().ForEach(t => t.Item2("Custom with flex filter")); } } public class Program { public static void Main(string[] args) { Standard std = new Standard(); std.ToDo += (msg) => Console.WriteLine("A: {0}", msg); std.ToDo += (msg) => Console.WriteLine("B: {0}", msg); std.Test(); Custom cust = new Custom(); cust.ToDo.Add((msg) => Console.WriteLine("A: {0}", msg)); cust.ToDo.Add((msg) => Console.WriteLine("B: {0}", msg)); cust.Test(); CustomWithFilter cwf = new CustomWithFilter(); cwf.Add("A", (msg) => Console.WriteLine("A: {0}", msg)); cwf.Add("B", (msg) => Console.WriteLine("B: {0}", msg)); cwf.Test("A"); cwf.Test("B"); Map m = new Map(); m.Add("A", (msg) => Console.WriteLine("A: {0}", msg)); m.Add("B", (msg) => Console.WriteLine("B: {0}", msg)); m.Test("A"); m.Test("B"); CustomWithFlexFilter cwff = new CustomWithFlexFilter(); cwff.Add("A", (msg) => Console.WriteLine("A: {0}", msg)); cwff.Add("B", (msg) => Console.WriteLine("B: {0}", msg)); cwff.Test(s => s.StartsWith("A")); cwff.Test(s => s!="A"); } } }