|
using System;
using System.Collections.Generic;
using System.Text;
namespace LambdaExpressions
{
public class LambdaSample
{
bool MatchNumbersBelow10(int n)
{
return n<10;
}
public int GetNumber_Method(List<int> numbers)
{
//gets the first number smaller than 10 in the list
return numbers.Find(MatchNumbersBelow10);
}
public int GetNumber_Anonymous(List<int> numbers)
{
//gets the first number smaller than 10 in the list
return numbers.Find(
delegate(int n)
{
return n<10;
}
);
}
public int GetNumber_Lambda(List<int> numbers)
{
//gets the first number smaller than 10 in the list
return numbers.Find(n=> n<10);
}
public void GetMatchesFromList(List<int> matchValues)
{
List<int> numbers=GetNumbers(); //Get a list of numbers to search in.
//Get the first number in the numbers list that is also contained in the matchValues list.
int result=numbers.Find(n=> matchValues.Contains(n));
}
public void DoStuffWithLambdas()
{
List<int> numbers=GetNumbers();
//find the first number in the list that is below 10
int match=numbers.Find(n=> n<10);
//print all the numbers in the list to the console
numbers.ForEach(n=> Console.WriteLine(n));
//convert all the numbers in the list to floating-point values
List<float> floatNumbers=numbers.ConvertAll<float>(n=> (float)n);
//sort the numbers in reverse order
numbers.Sort((x,y) => y-x);
//filter out all odd numbers
numbers.RemoveAll(n=> n%2!=0);
}
//helper function to get some sample numbers to work with
internal List<int> GetNumbers()
{
List<int> numbers=new List<int>();
Random rand=new Random();
for(int i=0;i<20;i++)
numbers.Add(rand.Next(0,20));
numbers.Add(1);
return numbers;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
My main goal as a developer is to improve the way software is designed, and how it interacts with the user. I like designing software best, but I also like coding and documentation. I especially like to work with user interfaces and graphics.
I have extensive knowledge of the .NET Framework, and like to delve into its internals. I specialize in working with VG.net and MyXaml. I also like to work with ASP.NET, AJAX, and DHTML.