Thursday, March 15, 2007

Using Anonymous methods

In a previous post about guidelines for programming in C#2.0, I had written about how I did not understand one of the guidelines of using "ForEach via an Anonymous method predicate". Well now I know. And I illustrate with some examples below. These examples show the use of the ForEach as well as the use of Anonymous methods.
using System;
using System.Collections.Generic;
//A test class to insert into a List

public class TestClass
{
    string _string;
    int _number;
    public TestClass(int num, string s)
    { _string = s; _number = num;}
    public int Number { get{ return _number;}}
    public string String{ get {return _string;}}
}
public class MyClass
{
    public static void Main()
    {
        //Finding Even Integers in List;
        List<int> integers = new List<int>();
        for(int i=1; i<=10; i++) integers.Add(i);
        //find even numbers using anonymous methods
   List<int> even = integers.FindAll(delegate(int i)
            {
                return i%2==0;
            });
        WL("Even Numbers");
  //Here is an example of using ForEach - and the Anonymous methods
  //The one thing i still dont understand is why this is more
  //efficient than using foreach directly.
        even.ForEach(delegate(int i){Console.Write(i + " ");});

        //Computing Sum of Integers in List<T>
        int sum=0;
        integers.ForEach(delegate(int i){ sum+=i; });
        WL("");
        WL("Sum " + sum);
       
        //Sort TestClasss in List<T>
        List<TestClass> testClass = new List<TestClass>();
        testClass.Add(new TestClass(10,"Milk"));
        testClass.Add(new TestClass(5,"Cheese"));
        testClass.Sort(delegate(TestClass x, TestClass y){
                   return Comparer<int>Default.Compare(x.Number,y.Number);
            });
        WL("Sorted TestClass");
        testClass.ForEach(delegate(TestClass o){WL(o.Number + " " + o.String);});

        RL();
    }
    #region Helper methods
    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }
    private static void RL()
    {
        Console.ReadLine();   
    }
    #endregion
}

No comments: