Wednesday, January 14, 2015

Anonymous Methods

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AnonymousMethods
{

    public partial class Form1 : Form
    {
        public delegate bool MyPredicate(int n);
        List<int> intList = new List<int>();



        Random rand = new Random();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //initialize intList with random values
            for (int i = 1; i <= 50; i++)
            {
                intList.Add(rand.Next(-99, 100));
            }
            Display(intList);
        }
        //display method to display any list
        private void Display(List<int> list)
        {
            listBox1.Items.Clear();
            foreach (int n in list)
                listBox1.Items.Add(n);

        }

        private void btnGetOddValues_Click(object sender, EventArgs e)
        {
            MyPredicate predicate = delegate(int n)
            {
                return n % 2 != 0;
            };
            List<int> oddList = FindAll(predicate);
            Display(oddList);
        }

        //what is a method? 
        //a method is a block of code with address
        //What is a method name?
        //A method name is an address.
        //====================================================
        private List<int> FindAll(MyPredicate predicate)
        {
            List<int> list = new List<int>();
            //write code to return all the odd values of the intList
            foreach (int n in intList)
            {
                //if (IsOdd(n))
                //{
                //    oddList.Add(n);
                //}
                if (predicate(n))
                {
                    list.Add(n);
                }
            }
            return list;

        }

        private void btnEvenPositive_Click(object sender, EventArgs e)
        {
            MyPredicate predicate = delegate(int n)
            {
                return n % 2 == 0 && n > 0;
            };
            List<int> evenPositiveList = FindAll(predicate);
            Display(evenPositiveList);
        }

        private void btnOddNegatives_Click(object sender, EventArgs e)
        {
            MyPredicate predicate = delegate(int n)
            {
                return n % 2 != 0 && n < 0;
            };
            List<int> oddNegativeList = FindAll(predicate);
            Display(oddNegativeList);
        }
       
    }
}

No comments:

Post a Comment