private static void FilterExample() { var l = Enumerable.Range(0, 9).ToList(); ListUtil.Filter(l, i => i > 5); Console.WriteLine("Enter number 0..9"); var k = Console.ReadKey().KeyChar - '0'; Console.WriteLine(); Console.WriteLine("Anonymous filter (>)"); ListUtil.Filter(l, i => i > k); Console.WriteLine(); Console.WriteLine("Delegate filter (<)"); //k++; Func <int, bool> filterFun = delegate(int i) { return(i < k); }; ListUtil.Filter(l, filterFun); k++; ListUtil.Filter(l, filterFun); }
static void Main(string[] args) { var words = new List <string>() { "1", "12", "123", "1234", "12345", "12346", "1234567" }; Console.Write("Maximum length of string to include? "); int userMaxLength = int.Parse(Console.ReadLine()); // userMaxLength scope is in Main MyPredicate <string> predicate = item => item.Length < userMaxLength; // we create an anonymous method that uses a variable decalred outside of itself IList <string> shortWords = ListUtil.Filter(words, predicate); // this method is passed to another method ListUtil.Dump(shortWords); // and userMaxLength int is still available //Console.WriteLine("Changing the value of the scoped variable within the predicate:"); //userMaxLength = 0; //MyPredicate<string> predicate2 = item => { userMaxLength++; return item.Length <= userMaxLength; }; //IList<string> shortWords2 = ListUtil.Filter(words, predicate2); //ListUtil.Dump(shortWords2); }