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 LambdaExpressions
{
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 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 (predicate(n))
{
list.Add(n);
}
}
return list;
}
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 btnOddValues_Click(object sender, EventArgs e)
{
//MyPredicate predicate = delegate(int n)
//{
// return n % 2 != 0;
//};
MyPredicate predicate = n => n % 2 != 0;
List<int> oddList = FindAll(predicate);
Display(oddList);
}
private void btnEvenPositives_Click(object sender, EventArgs e)
{
//define a predicate for the even positives
//MyPredicate predicate = n => n > 0 && n % 2 == 0;
List<int> evenPositives = FindAll(n => n > 0 && n % 2 == 0);
Display(evenPositives);
}
private void btnOddNegatives_Click(object sender, EventArgs e)
{
List<int> oddNegatives = FindAll(n => n < 0 && n % 2 != 0);
Display(oddNegatives);
}
}
}
//Lab
///Define a delegate type that takes an array of strings and
///returns a boolean
///
///Create a List of strings (like names) and
///initialize it in form1_load, with at least 20 names
///
///Write a FindAll method that return all the strings that
///satisfy the predicate condition,passed to it
///
///use lambda expression
///to get all the names whose length is greater than a certain
///value read from user
///
/// to get all the names that starts with a certain letter
/// read from user

No comments:
Post a Comment